Match Guards and Bindings
Add conditions and capture values.
What Is a Match Guard?
A match guard is an extra if condition added to a match arm. The arm only fires when the pattern matches and the condition is true.
It lets you split one variant into finer cases based on its data.
match number {
Some(n) if n > 0 => println!("positive"),
Some(n) => println!("zero or negative"),
None => println!("no number"),
}Guard Syntax
Write the pattern, then if condition, then =>. The condition can use any variables the pattern bound.
If the guard is false, Rust moves on to try the next arm.
fn main() {
let n = 4;
match n {
x if x % 2 == 0 => println!("even"),
_ => println!("odd"),
}
}All lessons in this course
- Defining Your First Enum
- Matching on Enum Variants
- Enums with Data
- Match Guards and Bindings