BeginnerLesson 4 of 155 min read

Functions, Control Flow, match and Option

Learn Rust functions and expressions, if and loops as expressions, match with guards and ranges, and Option instead of null, with every result verified independently.

In this lesson you will

  • Write functions and use expressions
  • Use loops and if as expressions
  • Use match with ranges and guards
  • Use Option instead of null

About 28 minutes

Which turbines need attention?

Ines wants to classify each wind speed reading as calm, working, strong or storm, to find the first reading above a limit, and to look up a turbine by number without crashing when it does not exist. Rust offers expressive tools for each of these, and one idea underlies them: almost everything is an expression that produces a value. A block returns the value of its last expression, if and match are expressions, and a function returns the value of its final expression when there is no semicolon.

A function is declared with fn, typed parameters and an optional return type after an arrow. The loops are loop, which repeats until you break, and can break with a value, while and for, where for iterates over anything that can be iterated, such as a range 1..=5. The match expression compares a value against patterns and must cover every possibility, which the compiler checks. Patterns can be values, ranges, alternatives with the bar, and can have guards with if. Rust has no null. A value that may be absent is an Option, either Some(value) or None, and you must handle both cases before you can use the value, so the billion-dollar mistake of unexpected nulls cannot happen.

Feature Example
Function fn double(x: i32) -> i32 { x * 2 }
if expression let label = if x > 5 { “big” } else { “small” };
Range loop for i in 1..=5 { }
match with range 0..=5 => “calm”
Guard n if n % 2 == 0 => “even”
Option Some(3), None
fn classify(speed: f64) -> &'static str {
    match speed as u32 {
        0..=3 => "calm",
        4..=14 => "working",
        15..=24 => "strong",
        _ => "storm",
    }
}

fn find_turbine(id: u32) -> Option<&'static str> {
    match id {
        1 => Some("North"),
        2 => Some("South"),
        _ => None,
    }
}

fn main() {
    let speeds = [1.5, 8.0, 14.9, 15.0, 22.3, 31.0, 3.9];
    let mut counts = [0; 4];
    for s in speeds.iter() {
        let c = classify(*s);
        let i = match c { "calm" => 0, "working" => 1, "strong" => 2, _ => 3 };
        counts[i] += 1;
        println!("{:>5} m/s -> {}", s, c);
    }
    println!("calm {}, working {}, strong {}, storm {}", counts[0], counts[1], counts[2], counts[3]);
    let first_strong = speeds.iter().position(|&s| s >= 15.0);
    println!("first reading at or above 15: {:?}", first_strong);
    let mut n = 0;
    let steps = loop {
        n += 7;
        if n >= 100 { break n / 7; }
    };
    println!("loop with a break value: n = {}, steps = {}", n, steps);
    let parity = |x: i32| match x { v if v % 2 == 0 => "even", 1 | 3 | 5 | 7 | 9 => "small odd", _ => "other odd" };
    println!("parity: {} {} {}", parity(4), parity(7), parity(11));
    for id in [1, 2, 7] {
        match find_turbine(id) {
            Some(name) => println!("turbine {} is {}", id, name),
            None => println!("turbine {} does not exist", id),
        }
    }
    let name = find_turbine(9).unwrap_or("unknown");
    let label = if find_turbine(1).is_some() { "found" } else { "missing" };
    println!("unwrap_or: {} | if as an expression: {}", name, label);
}
  1.5 m/s -> calm
    8 m/s -> working
 14.9 m/s -> working
   15 m/s -> strong
 22.3 m/s -> strong
   31 m/s -> storm
  3.9 m/s -> calm
calm 2, working 2, strong 2, storm 1
first reading at or above 15: Some(3)
loop with a break value: n = 105, steps = 15
parity: even small odd other odd
turbine 1 is North
turbine 2 is South
turbine 7 does not exist
unwrap_or: unknown | if as an expression: found

The match with ranges classified the seven readings into 2 calm, 2 working, 2 strong and 1 storm. The compiler insisted on the final underscore arm, since the ranges alone do not cover every number, which is the exhaustiveness check that prevents forgotten cases. The boundary behaves as the ranges say: 14.9 truncates to 14 and is working, and 15.0 is strong. The position method returned Some(3), the index of the first reading at or above 15, wrapped in an Option, because there might have been none.

The loop expression broke with a value: it added 7 until n reached 105 and produced the step count 15 as its result. The closure with guards sorted numbers into “even”, “small odd” and “other odd”, using the bar for alternatives and an if guard. The turbine lookup returned an Option, and the match handled both cases: turbines 1 and 2 exist, and turbine 7 gave the message that it does not exist instead of a crash. unwrap_or supplied a default for the missing turbine 9, and the if expression produced the label “found” directly.

Check by hand: as integers, the readings 1.5, 8.0, 14.9, 15.0, 22.3, 31.0 and 3.9 become 1, 8, 14, 15, 22, 31 and 3, which fall in calm (1 and 3), working (8 and 14), strong (15 and 22) and storm (31). The loop reaches 15 x 7 = 105. Python classified the same numbers with the same bounds and got {‘calm’: 2, ‘storm’: 1, ‘strong’: 2, ‘working’: 2}.

Avoid unwrap in real code

unwrap panics on None. It is fine in examples and tests. In production code, handle the None case with match, if let, unwrap_or or the ? operator, which lesson 8 introduces.

Let match be exhaustive

Do not add a catch-all arm if you can list the cases. Then, when someone adds a new enum variant, the compiler points at every match that needs updating.

About this course

Every program in this lesson was compiled with rustc 1.97 (edition 2021) and run while the course was written. Rust releases every six weeks and its compiler messages improve all the time, so check doc.rust-lang.org for the current edition and wording.

Practice

Add a “gale” class for speeds from 25 to 29 and make storm start at 30, and check the boundary values. Write a function that returns the average of a slice as an Option, None for an empty slice. Use if let to print the result when present.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does a block with no final semicolon do?

  1. Returns the value of its last expression
  2. Returns nothing
  3. Is an error
  4. Repeats

Rust is expression-oriented.

Why was the underscore arm required in the match?

  1. It is style
  2. Rust requires it always
  3. It speeds up the match
  4. The ranges did not cover every number

match must be exhaustive.

What does Option replace?

  1. Exceptions
  2. Loops
  3. Macros
  4. Null

Some(value) or None.

What does break n / 7 do in a loop?

  1. Divides n
  2. Skips an iteration
  3. Ends the loop with a value
  4. Prints n

loop can be an expression.

What does unwrap do on None?

  1. Returns zero
  2. Returns an empty string
  3. Panics
  4. Does nothing

Prefer unwrap_or or match.

Summary

  • Functions, blocks, if, loop and match are expressions that produce values.
  • match must be exhaustive; ranges and guards make patterns expressive.
  • Option replaces null and forces you to handle absence.
  • Avoid unwrap outside examples and tests.

Next lesson

Lesson 5 covers structs, enums and impl blocks.

Questions

What is the difference between loop and while?

loop repeats until you break and can return a value with break. while checks a condition before each pass.

What is if let?

A short form of match for one pattern, as in if let Some(x) = value { ... }.

Can match arms return different types?

No. Every arm must produce the same type, because match is an expression with one type.

Progress is saved in this browser.