capypad
0 day streak
rust / intermediate
Snippet

Match Guards and @ Binding in Rust

Match guards add conditional logic to patterns using 'if' expressions, while the @ operator binds matched values to variables within the pattern itself. This combination allows you to both filter and capture data in a single match arm.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
fn classify_age(age: u32) -> &'static str {
match age {
0..=12 => "child",
13..=19 if age % 2 == 0 => "teen even",
13..=19 => "teen odd",
n @ 20..=65 => if n >= 50 { "middle aged" } else { "young adult" },
_ => "senior"
}
}
 
fn main() {
println!("{}", classify_age(25)); // middle aged
println!("{}", classify_age(14)); // teen odd
println!("{}", classify_age(16)); // teen even
}
Breakdown
1
13..=19 if age % 2 == 0
Match guard filters the range 13-19 to only even ages
2
n @ 20..=65
@ binding captures the matched age value into variable n for use in the arm body
3
if n >= 50 { ... }
Guard creates a second condition on the already matched range