MARY.WIN

RUSTY — BEGINNER — B03

Functions, expressions and control
flow

Write a function whose last line is its answer, loop three ways, and sort numbers into bands with range patterns.
Lesson 3 of 9 in Rust beginner track. Before you start: Lesson 2.

You write a two-line function, double(). It promises an i32 and multiplies its argument by two. The compiler refuses it with error[E0308]: mismatched types: expected i32, found ().

The bug is one semicolon. By the end of this lesson you'll see it before the compiler does, and you'll be able to say what that one character changed.

This lesson covers functions with typed parameters and a return type, the difference between an expression and a statement, building text with format!, the three loops (for, while and loop), ranges, and range patterns in match. It uses match only for range patterns; Lesson 6 teaches match in full, including exhaustiveness. It assumes Lesson 2's let, mut and number types.

Take a look at Example 1.

Example 1. One semicolon too many (examples/compile-fail/f03_semicolon.rs)

fn double(n: i32) -> i32 {
    n * 2;
}

fn main() {
    println!("{}", double(4));
}

Before you compile it, predict the problem. Then, from the examples folder, hand it to the compiler:

TERMINAL
rustc --edition=2024 compile-fail/f03_semicolon.rs
error[E0308]: mismatched types
 --> compile-fail/f03_semicolon.rs:1:22
  |
1 | fn double(n: i32) -> i32 {
  |    ------            ^^^ expected `i32`, found `()`
  |    |
  |    implicitly returns `()` as its body has no tail or `return` expression
2 |     n * 2;
  |          - help: remove this semicolon to return this value

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0308`.

We'll take that message apart after a function that works.

Where is the return?

In PHP you'd write function shippingCents(int $weightGrams): int. Rust writes the same promise in nearly the same place. Take a look at Example 2, a small shipping calculator.

Example 2. Functions, ranges and loops (examples/src/bin/b03_functions.rs)

// Lesson b03: functions, expressions and control flow.
fn shipping_cents(weight_grams: u32) -> u32 {
    // The last expression, with no semicolon, is the return value.
    if weight_grams <= 500 {
        499
    } else {
        499 + ((weight_grams - 500) / 250) * 100
    }
}

fn label(cents: u32) -> String {
    format!("${}.{:02}", cents / 100, cents % 100)
}

fn main() {
    for grams in [300, 500, 1000] {
        println!("{grams} g -> {}", label(shipping_cents(grams)));
    }

    // Ranges: 1..4 stops before 4, 1..=3 includes 3.
    let mut total = 0;
    for n in 1..4 {
        total += n;
    }
    println!("sum 1..4 = {total}");
    println!("sum 1..=3 = {}", (1..=3).sum::<u32>());

    // `while` repeats while a condition is true.
    let mut countdown = 3;
    while countdown > 0 {
        println!("countdown {countdown}");
        countdown -= 1;
    }

    // `loop` can hand a value back through `break`.
    let mut tries = 0;
    let first_over_ten = loop {
        tries += 1;
        if tries * tries > 10 {
            break tries;
        }
    };
    println!("first number whose square is over 10: {first_over_ten}");
}

Run it with cargo run --quiet --bin b03_functions:

OUTPUT
300 g -> $4.99
500 g -> $4.99
1000 g -> $6.99
sum 1..4 = 6
sum 1..=3 = 6
countdown 3
countdown 2
countdown 1
first number whose square is over 10: 4

Start with shipping_cents(weight_grams: u32) -> u32. It takes a weight and returns cents. Parameter types are required. The -> u32 is the return type; a function with no -> returns (), the empty value. The body is one if. Up to 500 grams it evaluates to 499, and above that it evaluates the arithmetic. In Rust, if is an expression: it produces a value. Here that value is the function's return value, so neither branch says return.¹

One character decides

The function double held the position that it returned an i32. Its signature said so, after the arrow. Its body was one line, n * 2;, which multiplied the argument by two and then, because of the character at the end, set the result down like a cup left on the counter instead of handed across. main asked for double(4). The compiler reported that double implicitly returns () as its body has no tail or return expression.

Here's the rule behind that. An expression produces a value. A statement performs an action and produces none. If a block ends with an expression and no semicolon, that expression is the block's value, and it has a name: the tail expression. In Example 1, n * 2; ends with a semicolon, which turns it into a statement. The body now ends with no value, so it returns (). The signature promised i32. That's error E0308, mismatched types, and the help line points at the character: remove this semicolon to return this value.

Delete the semicolon and n * 2 becomes the tail expression, so double(4) returns 8. return n * 2; also works. The rule is about the block's last line, not a ban on return.

Building text with format!

label() in Example 2 turns cents into text with format!. cents / 100 gives the dollars, cents % 100 gives the cents, and {:02} pads to two digits; the third output line, 1000 g -> $6.99, is label(699). format! returns a String. println! prints. One builds text; the other writes it out.

Three loops

The PHP version of Example 2, php/b03_functions.php, reaches for foreach, a counting for, while, and a while (true) with a break in the middle. Rust has three loops, and each says what kind of stopping it does. for walks over something. while checks a condition first. loop runs until you break.

The for loop in Example 2 walks a range. 1..4 yields 1, 2 and 3; the end is left out. 1..=3 includes its end. Both sum to 6, as the output shows. while countdown > 0 checks before each pass, prints, and subtracts one. The plain loop has no condition at all. break tries ends it and hands back tries, so first_over_ten becomes 4.

You could write the countdown as a loop with a break too, and that would be, depending on whether the stopping condition belongs at the top of the body or in the middle and whether you need a value back when it stops, either a fair way to say what you mean or a while written the long way round, and in first_over_ten the value comes back through break.

Can a match arm say "one to nine"?

Here's a PHP habit. You label stock levels with match (true), and each arm is a comparison. The order of the arms does the work, and the bands live in your head. Take a look at Example 3.

Example 3. Bands as comparisons in PHP (php/b03_match.php)

<?php
function stockLabel(int $quantity): string
{
    return match (true) {
        $quantity <= 0 => 'out of stock',
        $quantity <= 9 => 'low stock',
        default => 'in stock',
    };
}

foreach ([-2, 0, 1, 9, 10, 250] as $quantity) {
    echo $quantity . ' -> ' . stockLabel($quantity) . PHP_EOL;
}

Rust lets the arm say the band. Example 4 is the same function with range patterns.

Example 4. Bands as range patterns (examples/src/bin/b03_range_patterns.rs)

fn stock_label(quantity: i32) -> &'static str {
    match quantity {
        ..=0 => "out of stock",
        1..=9 => "low stock",
        _ => "in stock",
    }
}

fn main() {
    for quantity in [-2, 0, 1, 9, 10, 250] {
        println!("{quantity} -> {}", stock_label(quantity));
    }
}

Run it with cargo run --quiet --bin b03_range_patterns, and run the PHP file with php php/b03_match.php. Both print the same six lines:

OUTPUT
-2 -> out of stock
0 -> out of stock
1 -> low stock
9 -> low stock
10 -> in stock
250 -> in stock

Inside match quantity, the arm ..=0 covers zero and below, 1..=9 covers one to nine, and _ covers everything else. A range pattern is a pattern, a shape the matched value is compared to, with three parts: a lower bound, the .. or ..=, and an upper bound. Either bound can be left off, and it matches every value between them. Ranges in patterns only work for numbers and char. For now, read each arm as "if the value is in this band".

Does 9 match the pattern 1..9? No. 1..9 stops before 9, just like the loop range. Write 1..=9 when the end belongs in the band.

So the arms say the bands, and the Rust output matches the PHP output line for line. Now ask where the bands came from. Is 9 "low stock" because someone who runs the stockroom said so, or because 9 was the number that came to mind? When the threshold moves, which file changes, and who notices? Should the number live in the arm at all?

Testing

Predict before you check. Which integers does 1..4 produce? And what does double(4) return once the semicolon is gone? It's 1, 2 and 3, and 8.

Then, without the lesson open, write double() from memory, once with the bug and once without, and say what the semicolon changed. You can forget the semicolon rule. E0308 will remind you, and its help line points at the character.

TL;DR

A Rust function declares its parameter types and its return type, and a function with no -> returns (). if is an expression, so a function can end on one and return its value. A block's last expression, with no semicolon, is its value; add a semicolon and it becomes a statement, the block returns (), and a function that promised i32 fails with E0308. format! builds a String; println! prints. for walks a range or a collection, while checks first, and loop runs until break, which can hand back a value. 1..4 leaves out its end and 1..=3 includes it, in loops and in range patterns alike. Next: vectors and hash maps.

¹ The PHP version in php/b03_functions.php writes the same rule with return, a ternary and intdiv, and prints the same nine lines.

The sources.

Programs, their output and the compiler's messages were recorded on rustc 1.100.0 on 2026-11-30. Book locators are to The Rust Programming Language (3rd edition), Programming Rust (3rd edition) and Learn Rust in a Month of Lunches.

SOURCES — 7
  • Rust Book ch. 3.3 "Functions", ch. 3.5 "Control Flow", ch. 19.3 "Pattern Syntax" [S20]
  • TRPL 3rd ed. ch. 3, Functions > Parameters and Functions with Return Values 13.8 (the book's own example shows E0308); Control Flow > Using if in a let Statement and Returning Values from Loops 13.10 [S17]
  • Programming Rust 3rd ed. ch. 6, Operators > Fields and Elements (.. excludes, ..= includes) [S18]
  • Rust standard library format! and std::fmt (the 0 flag) [S24]
  • Rust Reference "Patterns" (range patterns) [S25]
  • Rust by Example "Expressions" and "for and range" [S26]
  • PHP Manual "Returning values" and "match" [S27].

Rust Book: Functions · Rust Book: Control Flow · Rust Book: Pattern Syntax · Rust Reference: Patterns · Rust by Example: Expressions · Rust by Example: for and range · Rust std: format! · Rust std: fmt · PHP Manual: Returning values · PHP Manual: match

NOT CHECKED — 6
  • The repaired double() is described, not shown or run; that double(4) then returns 8 is arithmetic.
  • That 1..9 does not match 9 rests on the Rust Reference; no program on this page shows it.
  • {:02} zero-padding rests on the standard library's std::fmt documentation; none of the three books states it, and the output on this page has no value that needs padding.
  • The statement-and-expression rule was checked against The Rust Programming Language (3rd edition); the online Book's wording was not re-read for this page.
  • The Rust by Example pages were checked only for reachability.
  • Book locators were checked on 29 November 2026 and not re-read for this page.