RRust By Example
intermediateFlow Control

Match Guards

Add conditions to match arms with guards.

Match Guards

Add conditions to match arms with guards.

Difficulty

Intermediate

Code

rust
fn main() {
    let pair = (2, -2);
    match pair {
        (x, y) if x == y => println!("equal"),
        (x, y) if x + y == 0 => println!("sum to zero"),
        (x, _) if x % 2 == 1 => println!("first is odd"),
        _ => println!("no match"),
    }
}

Explanation

Match guards add conditions with if after patterns.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the flow-control category to build a complete understanding of this topic.

More Flow Control Examples