capypad
0 day streak
rust / intermediate
Snippet

Pattern Matching with Guard Expressions

Guard expressions in match arms allow you to add additional conditions beyond pattern matching. The `if` condition after the pattern is evaluated only if the pattern matches, enabling complex filtering logic within match expressions. Guards combine pattern destructuring with boolean conditions.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
fn classify_number(n: i32) -> &'static str {
match n {
n if n < 0 && n % 2 == 0 => "negative even",
n if n < 0 => "negative odd",
n if n == 0 => "zero",
n if n > 0 && n < 100 => "small positive",
n if n >= 100 && n % 2 == 0 => "large even",
_ => "large odd",
}
}
 
fn main() {
println!("{}", classify_number(-4)); // negative even
println!("{}", classify_number(50)); // small positive
println!("{}", classify_number(200)); // large even
}
Breakdown
1
n if n < 0 && n % 2 == 0 =>
Guard checks both negativity and evenness after pattern binds n
2
n if n < 0 =>
Guard for any negative number not caught by previous arm
3
n if n >= 100 && n % 2 == 0 =>
Guard combining multiple conditions for large even numbers
4
_ => "large odd"
Wildcard catches remaining cases not matched by guards