Sub topic 9
Match guards and @ bindings
This chapter assumes you can write a basic match, know the range and or-patterns from the previous chapters, and understand destructuring of enums and structs. It covers two tools that refine a pattern: guards, which add a condition, and @ bindings, which name a value while you test it.
Match guards
A match guard is an if condition placed after a pattern. The arm runs only when the pattern matches and the condition is true. Patterns can only describe the shape of a value. A guard lets you test anything else, such as a method call or a comparison with another variable.
fn classify(n: i32) -> &'static str {
match n {
i32::MIN..=-1 => "negative",
0 => "zero",
x @ 1..=9 if x % 2 == 0 => "small even",
1..=9 => "small odd",
10 | 100 | 1000 => "power of ten",
_ => "other",
}
}
fn main() {
for n in [-5, 0, 4, 7, 100, 42] {
println!("{n}: {}", classify(n));
}
}Arms are tried from top to bottom. The value 4 matches the pattern 1..=9, and the guard x % 2 == 0 is true, so the third arm wins. The value 7 passes the pattern but fails the guard, so matching continues to the next arm.
Guards and exhaustiveness
The compiler does not reason about guard conditions. An arm with a guard never counts toward covering a case. Even if your guards happen to cover every value, you still need an arm without a guard, such as _, or the match fails to compile with a non-exhaustive error.
Guards and or-patterns
A guard applies to the whole or-pattern, not to one alternative. In 1 | 2 | 3 if flag, the condition flag is checked whichever alternative matched. If you want different conditions for different values, write separate arms.
@ bindings
The name @ pattern form tests a value against a pattern and also binds the whole value to name. Without it, a range pattern such as 1..=9 matches the value but gives you no variable to use in the arm body.
The next example uses @ inside an enum variant and a struct field.
enum Event {
Key(char),
Click { x: i32, y: i32 },
}
fn describe(e: Event) -> String {
match e {
Event::Key(c) if c.is_ascii_digit() => format!("digit {c}"),
Event::Key(c @ 'a'..='z') => format!("lowercase {c}"),
Event::Key(_) => "other key".to_string(),
Event::Click { x, y: y @ 0..=99 } => format!("top click at {x},{y}"),
Event::Click { x, y } => format!("click at {x},{y}"),
}
}
fn main() {
println!("{}", describe(Event::Key('7')));
println!("{}", describe(Event::Key('q')));
println!("{}", describe(Event::Key('!')));
println!("{}", describe(Event::Click { x: 5, y: 20 }));
println!("{}", describe(Event::Click { x: 5, y: 300 }));
}Here y: y @ 0..=99 reads as "match the field y, require it to be in 0 to 99, and bind it to the name y". Compare this with a guard such as Event::Click { x, y } if (0..=99).contains(&y). Both work. The @ form keeps the test inside the pattern, which is shorter for ranges and literals. A guard is needed when the condition calls a method or involves more than one variable.
Common errors
- Missing fallback arm. Guarded arms do not prove exhaustiveness, so add a final unguarded arm.
- Wrong arm order. A broad arm placed above a narrower one hides it. The compiler warns about unreachable patterns only when the earlier arm has no guard.
- Binding on both sides of
@. Before Rust 1.56,name @ Some(inner)was rejected because both names bind the same data. Current stable Rust accepts it, but with non-Copydata the two bindings cannot both move the value.
Exercise
In match n { x if x > 0 => "positive", x if x <= 0 => "not positive" } where n is an i32, why does this fail to compile, and how do you fix it?
Show answer
The compiler ignores guard conditions when checking exhaustiveness, so it reports that the match is not exhaustive. Make the last arm unguarded, for example _ => "not positive", or use x => "not positive".