Skip to content
RustLearn

Module 03 — Control Flow & Functions

Goal

Rust is expression-oriented: if, match and even loops produce values. Write well-typed functions and stop reaching for the statements you know from other languages.

Start here — what this module is really about

There is one idea in this module, and it changes how your Rust looks: most things in Rust produce a value.

In many languages there is a firm line between a statement (something that does work) and an expression (something that produces a value). if is usually a statement: it runs one branch or the other, and if you want a value out of it you declare a variable first and assign inside each branch.

In Rust, if is an expression. So is a block of braces. So is match, which you meet properly in module 07. That means you can write:

rust
let status = if count > 10 { "many" } else { "few" };

instead of declaring status empty and filling it in later. This is not a style preference. It means fewer values start life uninitialised or mutable, which in turn means the compiler can prove more about your program — the same theme as module 02, arriving from a different direction.

The one rule you need to make it work is about the semicolon. A semicolon discards the value of an expression. So x + 1 at the end of a block is the block's value, while x + 1; throws it away and the block produces nothing. Almost every confusing early error in Rust is a semicolon that should not be there, or one that should.

The one sentence to remember: ask "what does this produce?", not "what does this do?" — and remember that a trailing semicolon means "produce nothing".

Learning objectives

  • Distinguish statements from expressions, and exploit the difference
  • Use if, loop, while, and for idiomatically
  • Break out of nested loops with labels, and return values from loop
  • Write functions with explicit signatures and understand why they're required
  • Understand divergence (!), early return, and panic!

3.1 Everything is an expression (almost)

Rust distinguishes:

  • Statements perform an action and return nothing. let x = 5; is a statement.
  • Expressions evaluate to a value. 5, x + 1, if a { 1 } else { 2 }, and a block { ... } are all expressions.
rust
let y = {
    let a = 3;
    a * a          // NO semicolon -> this is the block's value
};
assert_eq!(y, 9);

Add a semicolon and the block's value becomes ():

rust
let y = {
    let a = 3;
    a * a;         // semicolon -> statement -> block evaluates to ()
};
// y is ()

Mental model

A semicolon discards a value. The last expression in a block, written without a semicolon, is the block's result. This single rule explains 90% of "expected i32, found ()" errors.

TS ↔ Rust: JS has a ternary for expression-conditionals and if for statements. Rust has one construct that is both, so there is no ternary operator and none is needed.


The semicolon rule, made concrete

Three functions that look nearly identical and behave completely differently:

rust
fn a() -> i32 { 5 }         // ✅ returns 5 — no semicolon, so 5 is the block's value
fn b() -> i32 { 5; }        // ❌ error — the semicolon discarded it, so the block
                            //    produces nothing, but the signature promised i32
fn c() -> i32 { return 5; } // ✅ works, but nobody writes Rust this way

The compiler's message for b is worth internalising, because you will meet it often:

text
error[E0308]: mismatched types
  |
  | fn b() -> i32 { 5; }
  |           ---      ^ expected `i32`, found `()`
  |           |
  |           expected `i32` because of return type

That () is the unit type — Rust's way of saying "no meaningful value". Seeing expected i32, found () almost always means you left a semicolon on the last line. Delete it and the error goes away.

Reading the last line of every block as "this is what the block hands back" will save you hours.

Analogy — every question returns an answer

In statement-oriented languages, control flow is a set of instructions barked at a room: do this, now do that. In Rust it is closer to asking a question and being handed the answer — if, match and blocks all evaluate to a value you can bind or return. Once that clicks, the temporary let mut result; you would have declared first simply stops appearing in your code.

3.2 if expressions

rust
let number = 6;

if number % 4 == 0 {
    println!("divisible by 4");
} else if number % 3 == 0 {
    println!("divisible by 3");
} else {
    println!("neither");
}

Rules:

  • The condition must be a bool. if number { } is an error — there is no truthiness.
  • Parentheses around the condition are not used (though not an error, cargo fmt removes them).
  • Braces are mandatory even for one-liners.

As an expression:

rust
let condition = true;
let number = if condition { 5 } else { 6 };

Both arms must have the same type:

rust
// let n = if condition { 5 } else { "six" };  // ❌ E0308: `if` and `else` have
                                               //    incompatible types

An if without else used as an expression has type (), so this fails:

rust
// let n = if condition { 5 };   // ❌ expected integer, found ()

if let — a preview

rust
let maybe = Some(3);
if let Some(n) = maybe {
    println!("got {n}");
} else {
    println!("nothing");
}

// since Rust 1.65: let-else, for the "bail out early" shape
let Some(n) = maybe else {
    return;
};
println!("n is {n}");

Full treatment in module 07. Mentioned here because you'll see it everywhere.

3.3 The three loops

loop — infinite until you break

rust
let mut counter = 0;
let result = loop {
    counter += 1;
    if counter == 10 {
        break counter * 2;    // `loop` can return a value through break
    }
};
assert_eq!(result, 20);

loop is the right choice when the exit condition is naturally in the middle of the body (e.g. retry loops, read-until-EOF).

while — condition checked before each iteration

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

for — iterate anything iterable (use this by default)

rust
let a = [10, 20, 30, 40, 50];

for element in a {                 // consumes the array (Copy elements, so fine)
    println!("{element}");
}

for element in a.iter() {          // iterate by reference
    println!("{element}");
}

for (i, element) in a.iter().enumerate() {
    println!("index {i} = {element}");
}

for n in 1..4    { print!("{n} "); }   // 1 2 3     (exclusive)
for n in 1..=4   { print!("{n} "); }   // 1 2 3 4   (inclusive)
for n in (1..4).rev() { print!("{n} "); } // 3 2 1
for n in (0..20).step_by(5) { print!("{n} "); } // 0 5 10 15

for is preferred over indexed while loops because it eliminates off-by-one errors and lets the optimizer skip bounds checks.

Labels for nested loops

rust
'outer: for i in 0..5 {
    for j in 0..5 {
        if i * j > 6 {
            break 'outer;      // breaks the labelled loop, not just the inner one
        }
        if j == 3 { continue 'outer; }
        print!("{} ", i * j);
    }
}

Labelled break can also carry a value out of a labelled loop.


Choosing between the three loops

Rust gives you three looping constructs. They are not interchangeable, and picking correctly removes whole categories of bug:

rust
// 1. You know exactly what to visit → for. Use this ~90% of the time.
for item in &list {
    println!("{item}");
}

// 2. Repeat while a condition holds, count unknown → while.
while balance > 0 {
    balance -= payment;
}

// 3. Repeat until something inside decides to stop → loop.
let answer = loop {
    attempts += 1;
    if attempts == 3 { break attempts; }   // loop can hand back a value
};

Two things to notice:

  • for cannot go out of bounds. Indexing by hand (while i < list.len()) is where off-by-one errors come from; for visits exactly the real elements, so the bug cannot be written.
  • loop is the only one that produces a value, via break value. That is the idiomatic shape for "retry until it works, then give me the result".

Analogy — three loops, three jobs

loop is a night watchman: goes round forever until someone tells him to stop. while is a kettle: keep going as long as this condition holds. for is a postal round: here is the exact list of addresses, visit each once, done. Reaching for while i < len in Rust is walking a postal round while counting doors by hand — legal, slower, and the source of every off-by-one you will ever write.

3.4 Functions

rust
fn add(a: i32, b: i32) -> i32 {
    a + b            // no semicolon = return value
}

fn greet(name: &str) {           // no `->` means returns ()
    println!("Hello, {name}!");
}

fn main() {
    println!("{}", add(2, 3));
    greet("Ferris");
}

Rules:

  • Every parameter must be annotated. There is no inference across function boundaries.
  • The return type must be annotated unless it's ().
  • Functions can be declared in any order; there is no hoisting problem.
  • Naming convention: snake_case.

Why explicit signatures?

Type inference inside a function body is local and cheap. Inference across function boundaries would make error messages terrible and would make a change in one function silently ripple through the whole program. Explicit signatures are documentation the compiler checks.

Early return

rust
fn classify(n: i32) -> &'static str {
    if n < 0 {
        return "negative";     // explicit return needs `return` and a semicolon
    }
    if n == 0 {
        return "zero";
    }
    "positive"                 // final expression, no `return`, no semicolon
}

Both styles are idiomatic; use return for guard clauses and the bare expression for the main result.

The classic beginner error

rust
fn add(a: i32, b: i32) -> i32 {
    a + b;      // ❌ semicolon!
}
error[E0308]: mismatched types
  |
1 | fn add(a: i32, b: i32) -> i32 {
  |                           --- expected `i32` because of return type
2 |     a + b;
  |          - help: remove this semicolon to return this value

Nested functions and closures

Functions can be defined inside functions (useful for helpers that shouldn't escape):

rust
fn main() {
    fn double(x: i32) -> i32 { x * 2 }
    println!("{}", double(21));
}

Note that a nested fn cannot capture variables from the enclosing scope — for that you need a closure (module 14).

Diverging functions: the ! type

rust
fn forever() -> ! {
    loop {
        // never returns
    }
}

fn bail(msg: &str) -> ! {
    panic!("{msg}");
}

! is the "never" type. It coerces to any type, which is why this compiles:

rust
let x: i32 = if cond { 5 } else { panic!("nope") };

panic! unwinds the stack and aborts the thread. Use it for unrecoverable bugs (broken invariants), never for expected failure — that's Result's job (module 08).


Analogy — a signature is a contract

A function signature in Rust is not a suggestion to the reader, it is a contract enforced at the door: these types in, this type out, and this is who owns what afterwards. Because the contract is complete, you can understand a function's obligations without reading its body — and so can the compiler, which is why errors point at the call and not three layers down.

3.5 Putting it together: a small state machine

rust
#[derive(Debug, PartialEq)]
enum Light { Red, Yellow, Green }

fn next(light: &Light) -> Light {
    match light {
        Light::Red => Light::Green,
        Light::Green => Light::Yellow,
        Light::Yellow => Light::Red,
    }
}

fn main() {
    let mut light = Light::Red;
    for tick in 0..6 {
        println!("tick {tick}: {light:?}");
        light = next(&light);
    }
}

match gets its own module (07), but notice how naturally it composes with the expression model: every arm produces a Light, so the whole match is the return value.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
expressionCode that produces a value: 5, x + 1, an if, a match, a block.
statementCode that performs an action but produces no value, such as let x = 5;.
unit type ()The type meaning "no meaningful value". A function with no return type returns this.
armOne branch of a match, written pattern => result.
parameter / argumentParameter is the name in the definition; argument is the value passed at the call.
signatureA function's name, parameter types and return type — its contract with callers.
divergingCode that never produces a value because it always exits, like panic! or an infinite loop.

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
expected i32, found ()A block produced nothing where a value was required.Remove the semicolon from the block's last expression.
error[E0308]: if and else have incompatible typesThe branches produce different types, so the if has no single type.Make both branches produce the same type — "few" and "many", not "few" and 0.
error[E0317]: if may be missing an else clauseAn if used as a value has no else, so one path produces nothing.Add the else. Used as a value, an if must cover every case.
missing return typeA function produces a value but its signature does not declare one.Add -> Type to the signature.

Now make it stick: work through the drills for this module, then carry on to Module 04 — Ownership.