Sub topic 9
Match guards and @ bindings
This chapter assumes you can write a basic match over an enum, destructure variants that carry data, and read range and or-patterns. You should also know the difference between matching a value and matching a reference. Two extra features cover cases that patterns alone cannot express: match guards, which add a boolean condition to an arm, and @ bindings, which name a value while also testing it against a pattern.
Match guards
A match guard is an if condition placed after a pattern. The arm runs only when the pattern matches and the guard evaluates to true. If the guard is false, Rust moves on to the next arm.
enum Reading {
Temperature(f64),
Humidity(u8),
Offline,
}
fn describe(r: &Reading) -> String {
match r {
Reading::Temperature(t) if *t < 0.0 => format!("freezing: {t}"),
Reading::Temperature(t) if *t > 35.0 => format!("hot: {t}"),
Reading::Temperature(t) => format!("mild: {t}"),
Reading::Humidity(h) if *h > 100 => "invalid humidity".to_string(),
Reading::Humidity(h) => format!("humidity {h}%"),
Reading::Offline => "offline".to_string(),
}
}
fn main() {
let readings = [
Reading::Temperature(-3.5),
Reading::Temperature(21.0),
Reading::Humidity(140),
Reading::Humidity(55),
Reading::Offline,
];
for r in &readings {
println!("{}", describe(r));
}
}Because r is a reference, the bindings t and h are references too (&f64 and &u8). That is why the guards dereference them with *t and *h.
Arms are tried from top to bottom, so the order matters. The unguarded Reading::Temperature(t) arm acts as the fallback for temperatures that failed both guards. If you moved it above the guarded arms, they would never run.
Guards and or-patterns
A guard applies to the whole arm, including every alternative in an or-pattern. 1 | 2 | 3 if strict means (1 | 2 | 3) if strict. It does not mean 1 | 2 | (3 if strict).
fn label(n: u32, strict: bool) -> &'static str {
match n {
1 | 2 | 3 if strict => "low (strict)",
1 | 2 | 3 => "low",
_ => "other",
}
}
fn main() {
println!("{}", label(2, true));
println!("{}", label(2, false));
println!("{}", label(9, true));
}This prints low (strict), low, and other. If you need a different condition per alternative, write separate arms.
Guards and exhaustiveness
The compiler does not evaluate guards when it checks exhaustiveness. It cannot know whether x < 0 and x > 0 together cover everything, so it treats a guarded arm as one that might not match. Suppose you write this match without the final _ arm:
fn sign(n: i32) -> &'static str {
match n {
x if x < 0 => "negative",
0 => "zero",
x if x > 0 => "positive",
_ => unreachable!(),
}
}
fn main() {
println!("{} {} {}", sign(-4), sign(0), sign(9));
}It fails to compile with a non-exhaustive patterns error. The _ arm satisfies the compiler, but it is unreachable code that you must keep correct by hand. A range pattern removes the problem, because the compiler can check ranges:
fn sign(n: i32) -> &'static str {
match n {
i32::MIN..=-1 => "negative",
0 => "zero",
1..=i32::MAX => "positive",
}
}
fn main() {
println!("{} {} {}", sign(-4), sign(0), sign(9));
}Now the compiler verifies coverage. If you later change a range and leave a gap, the code stops compiling.
What a guard can do
A guard is an ordinary boolean expression. It can use any binding from the pattern, call functions, and read variables from the surrounding scope. Two comparisons between bindings are typical uses:
(a, b) if a == btests that two parts of a tuple are equal. No pattern can do this.Some(n) if n > limitcompares against a variable. Patterns only accept constants, not runtime values.
Guards should be free of side effects. Rust may evaluate a guard more than once in some or-pattern cases, and a reader does not expect a condition to change state.
@ bindings
Sometimes you want to test a value against a pattern and also keep the value. A plain binding such as n keeps the value but tests nothing. A range such as 1..=9 tests but binds nothing. The name @ pattern form does both.
enum Event {
Key(char),
Click { x: i32, y: i32 },
Scroll(i32),
}
fn handle(e: Event) -> String {
match e {
Event::Key(c @ 'a'..='z') => format!("lowercase {c}"),
Event::Key(c @ ('A'..='Z' | '0'..='9')) => format!("upper or digit {c}"),
Event::Key(other) => format!("other key {other:?}"),
Event::Click { x: px @ 0..=99, y } => format!("left strip click at {px},{y}"),
Event::Click { x, y } => format!("click at {x},{y}"),
Event::Scroll(d @ i32::MIN..=-1) => format!("up {}", d.unsigned_abs()),
Event::Scroll(d) => format!("down {d}"),
}
}
fn main() {
let events = [
Event::Key('q'),
Event::Key('7'),
Event::Key('!'),
Event::Click { x: 40, y: 12 },
Event::Click { x: 300, y: 8 },
Event::Scroll(-3),
Event::Scroll(5),
];
for e in events {
println!("{}", handle(e));
}
}Three details are worth noting:
- Inside variants.
c @ 'a'..='z'sits insideEvent::Key(...). The bindingcholds the character and the range limits which characters match. - Struct fields.
x: px @ 0..=99renames the field topxand constrains it. Theyfield uses the shorthand binding. - Parentheses. An or-pattern after
@needs parentheses:c @ ('A'..='Z' | '0'..='9'). Without them the|would split the arm into two alternatives, and only the first would bindc.
Binding a whole value and its parts
You can bind a whole value and also look inside it. Since Rust 1.56, bindings are allowed on both sides of the @.
#[derive(Debug, Clone, Copy)]
struct Point {
x: i32,
y: i32,
}
fn on_axis(p: Point) -> String {
match p {
whole @ (Point { x: 0, .. } | Point { y: 0, .. }) => format!("on an axis: {whole:?}"),
Point { x, y } => format!("off axis: ({x}, {y})"),
}
}
fn main() {
println!("{}", on_axis(Point { x: 0, y: 5 }));
println!("{}", on_axis(Point { x: 2, y: 3 }));
}Here the sub-patterns bind nothing, so whole takes the entire struct. If you bind the whole value and also bind parts of it by value, the value must be Copy. Otherwise the same data would be moved twice, and the compiler rejects it.
Combining guards and @ bindings
The two features work well together. The @ pattern captures a value that passed a coarse test, and the guard applies a finer condition to it.
fn bucket(n: i32) -> String {
match n {
x @ 1..=9 if x % 2 == 0 => format!("{x} is a small even number"),
x @ 1..=9 => format!("{x} is a small odd number"),
x @ (10 | 100 | 1000) => format!("{x} is a power of ten"),
x if x < 0 => format!("{x} is negative"),
_ => "something else".to_string(),
}
}
fn main() {
for n in [4, 7, 100, -2, 55] {
println!("{}", bucket(n));
}
}Without @, the first arm would have to match a plain x and recheck the range inside the guard. That would hide the range from the exhaustiveness checker and from the reader.
Choosing the right tool
| You want to... | Use | Checked for exhaustiveness |
|---|---|---|
| Match a fixed set of values | Literal or or-pattern | Yes |
| Match a span of values | Range pattern | Yes |
| Test and keep a value | `name @ pattern` | Yes |
| Compare bindings or call a function | Guard with `if` | No |
| Compare against a runtime variable | Guard with `if` | No |
Common mistakes
- Unreachable arms. An unguarded arm that matches everything the guarded arms do makes those arms useless if it comes first. Put guarded arms before the general arm.
- Forgetting parentheses around an or-pattern after
@. The compiler usually reports an error that the binding is not present in all alternatives. - Expecting guards to count toward coverage. A match that is complete only because of guards still needs a final unguarded arm.
- Guard type errors. When matching a reference, bindings are references, so the guard may need
*t. Alternatively, match with&patterns to bind the value directly.
Exercise
What does this program print, and why? let n = 5; let s = match n { x @ 1..=9 if x > 5 => "a", 1..=9 => "b", _ => "c" }; println!("{s}");
Show answer
It prints b. The first arm's pattern matches because 5 is in 1..=9, but the guard x > 5 is false, so Rust moves to the next arm. 1..=9 matches and has no guard, so the result is "b".
Exercise
Rewrite match n { x if x < 0 => "neg", 0 => "zero", x if x > 0 => "pos" } for an i32 n so that it compiles without an unreachable _ arm. What do you gain?
Show answer
Use range patterns: i32::MIN..=-1 => "neg", 0 => "zero", 1..=i32::MAX => "pos". The compiler can verify that the ranges cover every i32, so the match is exhaustive without a catch-all arm. If someone later edits a range and leaves a gap, compilation fails.
Exercise
Why does Event::Key(c @ 'A'..='Z' | '0'..='9') cause an error when the parentheses are removed from the or-pattern, and how do you fix it?
Show answer
Without parentheses, the | separates two top-level alternatives for the argument, so the second alternative '0'..='9' does not bind c and the alternatives disagree about which names they bind. Fix it by writing c @ ('A'..='Z' | '0'..='9').