Module 9 · Lesson 3 of 112

Variables, types, and control flow

Write basic Rust programs using immutable variables and shadowing, scalar and compound types, functions, and control flow.

  • Beginner to advanced
  • 8 min read
  • 21 min lab
What you will need

A Linux machine (Ubuntu 24.04 in WSL2, a VM, or a container) with internet access; VS Code with the rust-analyzer extension

Your place in the module
By the end you can 4 objectives
  • Write Rust programs using variables, scalar and compound types, functions, and control flow.
  • Distinguish debug from release integer-overflow behavior and make intent explicit with wrapping, checked, and saturating methods.
  • Explain how statements and expressions determine what a function returns.
  • Distinguish const from static and where each lives.
Video coming soonVariables, types, and control flow
The video for this lesson is being recorded. Read the lesson below in the meantime.
Recall first from Installing the toolchain and building with Cargo
  • rustup manages multiple toolchains, cross-compilation targets, and components such as clippy, rustfmt, and miri.
  • Editions (2015, 2018, 2021, 2024) let the language evolve without breaking old crates.
  • Cargo is the build system and package manager; Cargo.toml declares dependencies, Cargo.lock pins them.
01

Variables, mutability, and shadowing

3 min read

The previous lesson set up the toolchain and built a first Cargo project; now you write real Rust inside it. This lesson answers how to write basic Rust code with variables, types, and control flow.

In Rust, variables are immutable by default. That is the opposite of C, and it is a deliberate nudge toward the safety story: if a value cannot change, one part of your program cannot surprise another by changing it underneath it.

rust
fn main() {
    let x = 5;
    x = 6; // error: cannot assign twice to immutable variable
}

The let keyword introduces a binding. To make a binding mutable, add mut:

rust
fn main() {
    let mut x = 5;
    x = 6;
    println!("{x}"); // 6
}

is different from mut. Shadowing uses let again, and because it creates a brand new binding, it can even change the type:

rust
fn main() {
    let x = 5;
    let x = x + 1;              // x is 6
    {
        let x = x * 2;          // inner scope: x is 12
        println!("{x}");        // 12
    }
    println!("{x}");            // 6 again, inner binding is gone

    let spaces = "   ";
    let spaces = spaces.len();  // same name, new type
}

Shadowing lets you reuse a simple name as you transform a value, while keeping each intermediate binding immutable. With mut you would be locked to a single type and a single, ever-changing value; with shadowing each let is a fresh, read-only binding.

Type inference means you rarely write a type: let x = 5; infers i32, the default integer type. You annotate when the compiler cannot decide, most often with parse, and you must annotate every function parameter and return type, a deliberate rule that makes function signatures self-documenting and improves error messages.

Going deeperconst vs static, and where each lives

Rust has two ways to name a fixed value that is not a local variable. const is a value inlined at every use site, evaluated at compile time, with no fixed memory address:

rust
const MAX_POINTS: u32 = 100_000;

A const is just a number the compiler pastes in; there is no object to point at. static is different: it names a single object with a fixed address that lives for the whole program:

rust
static GREETING: &str = "hello";

Because a static has one address shared by all threads, mutating it is unsafe, and you must wrap changes in a synchronised type. In safe Rust you reach for static together with atomics or the interior-mutability types you will meet in a later lesson. On a bare-metal target, static mut and atomics are how you manage the small amount of globally shared state a microcontroller has, which is why the distinction between an inlined const and an addressed static matters in practice.

Shadowing through scopeslet x = 5let x = x +1x is 6inner let x= x * 2x is 12 inthis scopescope endsinner xdroppedx is 6againlet x = 5let x = x +1x is 6inner let x= x * 2x is 12 inthis scopescope endsinner xdroppedx is 6again
How shadowing rebinds a variable and how the inner binding ends when its scope closes
02

Scalar and compound types

4 min read

Rust is statically typed: the compiler knows the type of every value at compile time. Types come in two families. Scalar types hold a single value; compound types group several values.

The integer types are signed i8, i16, i32, i64, i128 and unsigned u8, u16, u32, u64, u128, plus the pointer-sized isize and usize, which are 64 bits on a 64-bit machine. An integer literal defaults to i32. Literals can be decimal 98_222, hex 0xff, octal 0o77, binary 0b1111_0000, or a byte b'A' for u8, and a suffix sets the type, as in 57u8. Underscores are visual separators only.

Try it below: toggle signed on and off to watch the same eight bits mean 255 or -1.

-1 in 8-bit two's complement is 0b11111111 = 0xFF; read as unsigned the same bits are 255, which is why 255u8 + 1 wraps to 0 in a release build.

  • value: -1
  • width: 8

The floating-point types are f32 and f64, both IEEE-754, with f64 the default. bool is one byte, and char is four bytes. That last one surprises C programrs: a Rust char is a , not an ASCII byte. 'π' and '本' are valid char values, and std::mem::size_of::<char>() is 4 on every platform, enough for supplementary-plane scalars outside the basic multilingual plane. When you need bytes you use u8; when you need text you use strings, which you will meet in a later lesson.

Going deeperInteger overflow: debug panics, release wraps

Rust gives the same arithmetic two different behaviours depending on the profile. In a debug build, overflow is checked and panics:

rust
fn main() {
    let mut n: u8 = 255;
    n = n + 1; // debug: panics with "attempt to add with overflow"
}

In a release build the checks are omitted for speed, and the value wraps in two's complement: 255 + 1 becomes 0. Relying on that wrap is treated as a bug, so when you genuinely want wrapping, say so with the standard library's method families, which behave the same in both profiles:

rust
let w = 255u8.wrapping_add(1);        // 0, always
let c = 255u8.checked_add(1);         // None
let (v, of) = 255u8.overflowing_add(1); // (0, true)
let s = 255u8.saturating_add(1);      // 255, clamped

For embedded code that counts ticks or computes checksums, wrapping_add is often exactly the right, explicit, portable behaviour, and it documents your intent in a way a bare + never does.

The compound types are tuples and arrays. A tuple groups a fixed number of values of possibly different types:

rust
fn main() {
    let tup: (i32, f64, u8) = (500, 6.4, 1);
    let (x, y, z) = tup;   // destructure
    println!("{} {} {}", x, y, z);
    println!("{}", tup.0); // index access
}

The empty tuple () is the unit type: the type of the empty tuple, representing no meaningful value and used as the return type of functions that return nothing. Every statement and every function that does not return a real value evaluates to ().

An array [T; N] holds a fixed number of values of one type, all on the stack:

rust
let a: [i32; 5] = [1, 2, 3, 4, 5];
let zeros = [0; 5];       // five zeros
let first = a[0];

A slice, written &[T], is a reference to some contiguous run of elements together with its length, which is known only at runtime. Arrays are for when the count never changes and you want the data on the stack; slices are how borrowed, variable-length data is viewed. You will use slices constantly once you meet references in the next lesson.

Integer types and their sizes8-biti8u816-biti16u1632-biti32u3264-biti64u64128-biti128u128pointerisizeusizesigned / unsigned; integer literalsdefault to i32
The signed and unsigned integer types at each width, with the i32 default marked
03

Functions and control flow

3 min read

Functions are declared with fn, use snake_case names, and can appear in any order. Every parameter needs a type, and a return type follows an arrow:

rust
fn main() {
    let x = plus_one(5);
    println!("{x}");
}

fn plus_one(x: i32) -> i32 {
    x + 1   // no semicolon: this is the return value
}

The distinction between statements and expressions is the heart of Rust's expression-based style. A statement performs an action and returns nothing; let x = 5; is a statement, and in fact its value is (), which is why you cannot write let x = (let y = 5);. An expression evaluates to a value. Blocks are expressions, so this works:

rust
fn main() {
    let y = {
        let x = 3;
        x + 1    // the block evaluates to 4
    };
    println!("{y}"); // 4
}

The same rule makes if an expression that can be assigned, and makes a loop able to hand a value out through break:

rust
fn main() {
    let number = if 3 < 5 { "small" } else { "large" };

    let mut counter = 0;
    let result = loop {
        counter += 1;
        if counter == 10 {
            break counter * 2;
        }
    };
    println!("{} {}", number, result);
}

A function with no return type returns (), the unit type. The opposite extreme is a :

rust
fn bail(msg: &str) -> ! {
    eprintln!("{msg}");
    std::process::exit(1);
}

The never type ! says this function does not return; loop {} without a break, panic!, and std::process::exit all have type !. Because a value of type ! can never exist, the compiler lets it coerce to any other type, which is why you can use a diverging call in any expression position. Note that ! is stable as a return type, but not yet usable everywhere as a general value type; the long-running never-type stabilisation is still settling some corners.

Control flow covers if, loop, while, and for. An if condition must be exactly a bool; Rust will not convert an integer to a truth value the way C does. Loops support break and continue, and a loop label disambiguates nested loops:

rust
fn main() {
    'outer: loop {
        loop {
            break 'outer;   // exits the labelled loop
        }
    }

    let mut n = 3;
    while n > 0 {
        println!("{n}");
        n -= 1;
    }

    for i in 1..5 {          // 1, 2, 3, 4
        println!("{i}");
    }
    for i in (1..=3).rev() { // 3, 2, 1
        println!("{i}");
    }

    let a = [10, 20, 30];
    for elem in a {
        println!("{elem}");
    }
}

The for loop works over any iterator, not just ranges. This is the idiomatic way to visit a collection: no manual index, no off-by-one, and the compiler generates the same tight loop as hand-written indexing. match, the other big control-flow construct, is the subject of a later lesson; the labs for this lesson keep to if and loops on purpose.

Statements versus expressionsStatementExpressionReturns a valuenoyesEnds withsemicolonyesusually notExamplelet x = 5;5 + 6Used as a valuecannotcan, e.g. anif or block
The difference between statements, which return nothing, and expressions, which yield a value

Key takeaways

  • Variables are immutable by default; reach for mut or shadowing deliberately.
  • Integer overflow panics in debug builds and wraps in release builds; use checked, wrapping, or saturating methods.
  • char is a four-byte Unicode scalar value, not a single byte.
  • A statement returns nothing and evaluates to (), while blocks and if are expressions, and a function returns the value of its last expression.
Reflect
  1. Explain to a colleague, in two sentences: write Rust programs using variables, scalar and compound types, functions, and control flow.
  2. Which objective are you least sure about? Re-read that section, then do its exercise in the practice pack.
  3. What surprised you when you ran the commands yourself?
On a real board

Repeat the key commands on your Raspberry Pi or lab board over SSH or the serial console. Note anything that behaves differently from your PC, such as missing tools, a BusyBox shell or a read-only filesystem.

References and further reading

Official documentation first. Links checked when the lesson was published.

Find your next step

↑ ↓ to move · Enter to open · Esc to close