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
ifafter a pattern is the guard, tested only on a match.n @ 1..=9binds the value and checks the range.|joins alternative patterns in one arm.
Keywords and builtins used here
Stringdescribefnfori32ifinmainmatch
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.
Step 3 of 4 in Pattern matching, step 21 of 39 in Language basics.