Examples of Basic Syntax in Rust: 3 Practical Examples for Beginners

If you’re trying to get your head around Rust, staring at the official book and endless docs can feel intimidating. Sometimes you just want clear, concrete examples of basic syntax in Rust: 3 practical examples you can copy, tweak, and actually understand. That’s what this guide is for. Instead of abstract theory, we’ll walk through real examples of basic syntax in Rust that you’ll actually use: variables, functions, control flow, and a tiny data-structuring example. Along the way, we’ll talk about why Rust code looks the way it does and how it compares to more familiar languages like Python or JavaScript. By the end, you won’t be a Rust expert, but you will be able to read simple Rust code without panicking, write small snippets on your own, and know where to go next. Think of this as your hands-on, no-nonsense tour of Rust’s basic building blocks in 2024–2025.
Written by
Taylor
Published
Updated

Let’s start with the first practical example of basic syntax in Rust and then build up from there. You’ll see that the best examples aren’t fancy; they’re the tiny pieces you’ll use everywhere.

All of these examples of basic syntax in Rust assume you have Rust installed (rustup is still the standard way in 2024–2025). If you don’t, the official Rust site has a quick installer:

  • Official Rust install instructions: https://www.rust-lang.org/learn/get-started

You can run each code sample with:

rustc main.rs
./main

on Linux/macOS, or:

rustc main.rs
main.exe

on Windows.


Example 1: Variables, Mutability, and Basic Types

The first example of basic syntax in Rust you’ll meet is how Rust handles variables and types. Rust is very opinionated about who can change what, and when.

Here’s a tiny program that shows off several examples of variables and types:

fn main() {
    // Immutable variable (default in Rust)
    let x = 5;
    println!("x is: {}", x);

    // Mutable variable
    let mut y = 10;
    println!("y starts as: {}", y);
    y = 15;
    println!("y is now: {}", y);

    // Explicit type annotation
    let z: i32 = 42;
    let pi: f64 = 3.14159;
    let is_rust_fun: bool = true;

    println!("z: {}, pi: {}, fun: {}", z, pi, is_rust_fun);
}

This single snippet already gives you several real examples of basic syntax in Rust: 3 practical examples just in one place:

  • let x = 5; shows an immutable binding.
  • let mut y = 10; shows a mutable binding.
  • let z: i32 = 42; shows explicit type annotation.

A Few More Concrete Variable Examples

To make these examples of basic syntax in Rust more realistic, here are a few everyday-style snippets.

String handling:

fn main() {
    let greeting = "Hello";        // string slice, fixed
    let mut name = String::from("Sam");  // owned String, growable

    name.push_str(" Smith");

    println!("{} {}!", greeting, name);
}

Shadowing (reusing a variable name with a new value or type):

fn main() {
    let spaces = "   ";
    let spaces = spaces.len();  // shadows with a new type (usize)

    println!("Number of spaces: {}", spaces);
}

These are some of the best examples of how Rust encourages clarity: you can change a variable’s value with mut, or you can shadow it when you conceptually want a “new” value.


Example 2: Functions and Return Values in Rust

Next up in our examples of basic syntax in Rust: 3 practical examples is functions. Rust’s function syntax is compact but strict about types.

Here’s a clean, realistic function example:

fn main() {
    let a = 7;
    let b = 5;

    let sum = add(a, b);
    println!("{} + {} = {}", a, b, sum);
}

fn add(x: i32, y: i32) -> i32 {
    x + y  // no semicolon = return this expression
}

In this example of a basic Rust function:

  • fn add(x: i32, y: i32) -> i32 shows parameter and return types.
  • The last line x + y has no semicolon, which means it’s the return value.

If you accidentally add a semicolon, you turn it into a statement returning (), and the compiler will complain. This is a very common beginner error, so if you see a confusing type error, check for stray semicolons.

Functions with Multiple Return Paths

Here’s a slightly more realistic function that uses an if expression to decide what to return.

fn main() {
    let temp_f = 90.0;
    let message = heat_warning(temp_f);
    println!("{}", message);
}

fn heat_warning(temp_f: f64) -> String {
    if temp_f > 100.0 {
        String::from("Danger: extreme heat")
    } else if temp_f > 85.0 {
        String::from("Caution: very warm")
    } else {
        String::from("Temperature is comfortable")
    }
}

This is one of those real examples where Rust’s expression-based style shines: if is an expression, so the whole if block becomes the return value of the function.

If you’re curious about safe handling of values and types, the official Rust book remains the go-to reference:

  • The Rust Programming Language (official book): https://doc.rust-lang.org/book/

Example 3: Control Flow – if, loop, while, and for

For the third of our examples of basic syntax in Rust: 3 practical examples, let’s look at control flow. You’ll use these every time you write Rust.

if Expressions

You saw if used in a function above. Here’s a slightly different example of basic syntax in Rust using if directly in main:

fn main() {
    let age = 20;

    if age >= 21 {
        println!("You can legally drink alcohol in the US.");
    } else if age >= 18 {
        println!("You are an adult, but not 21 yet.");
    } else {
        println!("You are under 18.");
    }
}

This is standard if syntax, but remember: if is an expression in Rust, so you can assign its result to a variable:

fn main() {
    let score = 87;

    let grade = if score >= 90 {
        'A'
    } else if score >= 80 {
        'B'
    } else if score >= 70 {
        'C'
    } else {
        'D'
    };

    println!("Grade: {}", grade);
}

Loops: loop, while, and for

Now for some looping examples of basic syntax in Rust. We’ll start from the simplest and move up.

An infinite loop with a break condition:

fn main() {
    let mut counter = 0;

    loop {
        counter += 1;
        println!("Counter: {}", counter);

        if counter == 3 {
            println!("Breaking out of the loop.");
            break;
        }
    }
}

A while loop that looks more familiar if you’re coming from C or JavaScript:

fn main() {
    let mut n = 5;

    while n > 0 {
        println!("{}...", n);
        n -= 1;
    }

    println!("Liftoff!");
}

A for loop that iterates over a range and over a collection:

fn main() {
    // Range: 1 to 5 (5 is excluded)
    for i in 1..5 {
        println!("i = {}", i);
    }

    let colors = ["red", "green", "blue"];

    for color in colors.iter() {
        println!("Color: {}", color);
    }
}

These loop snippets are some of the best examples of everyday control-flow syntax you’ll write in Rust.


Bonus Example: Structs and impl Blocks (A Tiny Data Model)

So far, our examples of basic syntax in Rust: 3 practical examples have focused on variables, functions, and control flow. Let’s add a bonus fourth category: defining your own data type with a struct and implementing methods on it with an impl block.

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn is_square(&self) -> bool {
        self.width == self.height
    }
}

fn main() {
    let rect = Rectangle { width: 10, height: 20 };
    let square = Rectangle { width: 15, height: 15 };

    println!("Rectangle area: {}", rect.area());
    println!("Is rectangle square? {}", rect.is_square());

    println!("Square area: {}", square.area());
    println!("Is square square? {}", square.is_square());
}

Here you get several more real examples of basic syntax in Rust in one place:

  • Defining a struct with named fields.
  • Implementing methods with impl and &self.
  • Calling methods with dot syntax: rect.area().

This is the point where Rust starts to feel like a modern systems language rather than a pile of low-level details.


Example 5: Pattern Matching with match and Option

In modern Rust (and especially in 2024–2025 codebases), pattern matching is everywhere. It’s hard to talk about examples of basic syntax in Rust without at least one match example.

Here’s a simple match on an integer:

fn main() {
    let day = 3;

    let name = match day {
        1 => "Monday",
        2 => "Tuesday",
        3 => "Wednesday",
        4 => "Thursday",
        5 => "Friday",
        6 => "Saturday",
        7 => "Sunday",
        _ => "Invalid day",
    };

    println!("Day {} is {}", day, name);
}

And here’s a more “Rusty” example using Option<T>:

fn main() {
    let maybe_number: Option<i32> = Some(10);

    let doubled = match maybe_number {
        Some(n) => n * 2,
        None => 0,
    };

    println!("Doubled value: {}", doubled);
}

This match example of handling Option is something you’ll see constantly in open-source Rust projects, especially as more companies adopt Rust for safety and reliability in 2024–2025.

If you’re curious about how Rust’s safety model compares to other languages, the National Institute of Standards and Technology has broader guidance on secure software development (not Rust-specific, but very relevant to why Rust is popular):

  • NIST Secure Software Development Framework: https://csrc.nist.gov/publications

Example 6: Basic Error Handling with Result

Another very common example of basic syntax in Rust is working with Result<T, E>. Even if you’re just writing toy scripts, you’ll bump into this quickly.

Here’s a tiny file-reading example:

use std::fs;
use std::io;

fn main() -> Result<(), io::Error> {
    let contents = fs::read_to_string("data.txt")?;
    println!("File contents:\n{}", contents);
    Ok(())
}

This gives you several real examples in one go:

  • A main function that returns Result<(), io::Error>.
  • The ? operator for propagating errors.
  • Using Ok(()) to signal success.

Patterns like this are all over modern Rust in 2024–2025, from CLI tools to web servers.

For a broader look at safe coding practices (again, language-agnostic but highly relevant to why Rust exists), you can browse resources from the U.S. Cybersecurity & Infrastructure Security Agency:

  • CISA Secure by Design guidance: https://www.cisa.gov/resources-tools

Pulling It Together: How to Practice These Rust Syntax Examples

We’ve walked through several examples of basic syntax in Rust: 3 practical examples and then some: variables, functions, control flow, structs, pattern matching, and simple error handling. That’s a lot of pieces, but you don’t need to memorize them.

Here’s a simple way to practice using these examples of basic syntax in Rust without getting overwhelmed:

  • Start a new main.rs.
  • Pick one of the short snippets above.
  • Type it out by hand (don’t just paste). Let the compiler complain.
  • Change one thing at a time: a type, a value, a branch in a match, a loop condition.
  • Re-run and see what breaks.

Rust’s compiler is famously strict, but that’s also why it’s trusted more and more in security-sensitive areas, from browsers to cloud infrastructure. The strictness you feel while learning these basic syntax examples is the same strictness that helps prevent entire classes of bugs.

If you want a structured path after you’re comfortable with these real examples, the official Rust book and the Rustlings exercises are the two best places to go next:

  • Rustlings exercises (hands-on practice): https://github.com/rust-lang/rustlings

Keep these examples of basic syntax in Rust nearby as a cheat sheet, and you’ll find that reading and writing simple Rust gets easier surprisingly fast.


FAQ: Common Questions About Rust Basic Syntax

What are some simple examples of basic syntax in Rust for absolute beginners?

Some of the simplest examples of basic syntax in Rust include:

  • Declaring variables with let and let mut.
  • Writing a tiny function like fn add(x: i32, y: i32) -> i32 { x + y }.
  • Using if and for to control program flow.
  • Printing with println!("value = {}", value);.

The code samples in this article give you multiple real examples you can paste into a main.rs and run immediately.

Can you give an example of a basic Rust function with parameters and a return value?

Yes. A classic example of a basic Rust function is:

fn square(n: i32) -> i32 {
    n * n
}

You would call it from main like this:

fn main() {
    let result = square(4);
    println!("4 squared is {}", result);
}

This example of a function shows parameter types, a return type, and an expression-based return.

How do if and match differ in Rust syntax?

if is great for simple true/false branching and can be used as an expression. match shines when you need to consider several patterns, such as different enum variants or ranges of values. Both are key examples of basic syntax in Rust, but match encourages you to think in terms of exhaustive cases, which often leads to safer code.

Are these basic syntax examples still valid for Rust in 2024–2025?

Yes. The core syntax you’ve seen here—variables, functions, control flow, structs, match, Option, and Result—has been stable for years and is used in current Rust projects today. Newer features keep arriving, but these examples of basic syntax in Rust remain the foundation you’ll build on.

Explore More Rust Code Snippets

Discover more examples and insights in this category.

View All Rust Code Snippets