Advanced Pattern Matching
Match Guards
Add Conditions to Patterns
A match guard refines a pattern with a boolean condition after the shape already matches.
Program
Play the program to choose a score and see which guarded arm classifies it.
match_guards.rs
fn main() {
let score = ;
let label = grade(score);
println!("{score}:{label}");
}
fn grade(score: i32) -> &'static str {
match score {
n if n >= 90 => "excellent",
n if n >= 60 => "pass",
_ => "retry",
}
}
fn main() {
let score = ;
let label = grade(score);
println!("{score}:{label}");
}
fn grade(score: i32) -> &'static str {
match score {
n if n >= 90 => "excellent",
n if n >= 60 => "pass",
_ => "retry",
}
}
fn main() {
let score = ;
let label = grade(score);
println!("{score}:{label}");
}
fn grade(score: i32) -> &'static str {
match score {
n if n >= 90 => "excellent",
n if n >= 60 => "pass",
_ => "retry",
}
}
guard
`n if n >= 60` matches only when the value also passes the condition.
arm order
The first matching guarded arm wins, so the excellent arm is checked before pass.
fallback
`_` catches values that did not satisfy any earlier guard.