21.10 Match Guards

A match guard is an additional if condition applied to a pattern:

fn classify_age(age: i32) {
    match age {
        n if n < 0 => println!("Invalid age"),
        n @ 0..=12 => println!("Child: {}", n),
        n @ 13..=19 => println!("Teen: {}", n),
        n => println!("Adult: {}", n),
    }
}

fn main() {
    classify_age(-1);
    classify_age(10);
    classify_age(17);
    classify_age(30);
}

Only if the pattern matches and the guard returns true does that arm run.

  • n if n < 0: Uses a match guard to detect a negative age.
  • n @ 0..=12 and n @ 13..=19: Binds n and simultaneously checks it against a range.
  • n (the “catch-all” arm): Everything else is treated as an adult age.