typestar

Match guards and bindings in Rust

A guard adds a condition to an arm; @ keeps the value you matched on.

fn describe(n: i32) -> String {
    match n {
        0 => "zero".to_string(),
        n @ 1..=9 => format!("single digit {n}"),
        n if n % 2 == 0 => format!("even {n}"),
        10 | 100 | 1000 => "round".to_string(),
        _ => "odd and large".to_string(),
    }
}

fn main() {
    for n in [0, 7, 42, 100, 33] {
        println!("{}", describe(n));
    }
}

How it works

  1. if after a pattern is the guard, tested only on a match.
  2. n @ 1..=9 binds the value and checks the range.
  3. | joins alternative patterns in one arm.

Keywords and builtins used here

The run, in numbers

Lines
15
Characters to type
303
Tokens
117
Three-star pace
90 tpm

At the three-star pace of 90 tokens a minute, this run takes about 78 seconds.

Type this snippet

Step 3 of 4 in Pattern matching, step 21 of 39 in Language basics.

← Previous Next →