Match Guards
When matching, you can add a guard to a pattern. This is an arbitrary Boolean expression which will be executed if the pattern matches:
1. #[rustfmt::skip]
2. fn main() {
3. let pair = (2, -2);
4. println!("Tell me about {pair:?}");
5. match pair {
6. (x, y) if x == y => println!("These are twins"),
7. (x, y) if x + y == 0 => println!("Antimatter, kaboom!"),
8. (x, _) if x % 2 == 1 => println!("The first one is odd"),
9. _ => println!("No correlation..."),
10. }
11. }
Key Points:
- Match guards as a separate syntax feature are important and necessary when we wish to concisely express more complex ideas than patterns alone would allow.
- They are not the same as separate
ifexpression inside of the match arm. Anifexpression inside of the branch block (after=>) happens after the match arm is selected. Failing theifcondition inside of that block won’t result in other arms of the originalmatchexpression being considered. - You can use the variables defined in the pattern in your if expression.
- The condition defined in the guard applies to every expression in a pattern with an
|.
