21.10 Match Guards
A match guard is an additional if condition on a pattern. The pattern must match, and the guard must evaluate to true, for that arm to execute:
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); }
n if n < 0: Uses a guard to check for negative numbers.n @ 0..=12/n @ 13..=19: Bindsnand also enforces the range.n(the catch-all): Covers everything else.