Patterns can destructure tuples and add if guards, so one match expresses several conditions.

Program

Play the program to classify a point with a match guard.

pattern_match.rs
Replay: real traced execution (multi-file project)
fn main() {
    let point = (2, -3);
    let label = match point {
        (0, 0) => "origin",
        (x, _) if x > 0 => "right",
        _ => "other",
    };
    println!("{label}");
}
  1. point ← (2, -3), label ← "right"

    1fn main() {2    let poin→ (2, -3)t = (2, -3);3    let labe→ "right"l = match poin(2, -3)t {4        (0, 0) => "origin",5        (x, _) if x > 0 => "right",6        _ => "other",7    };8    println!("{label}");9}
    outputright

Follow the Trace

  1. point starts as (2, -3).
  2. The (0, 0) arm does not match.
  3. The (x, _) if x > 0 arm matches because x is 2.
  4. label becomes right.
  5. The program prints right. | trace point | value | | --- | --- | | point | (2, -3) | | matched arm | (x, _) if x > 0 | | x | 2 | | label | right | | stdout | right |
destructuring `(x, _)` pulls the first tuple field into `x`.
match guard `if x > 0` adds a condition to an arm.
order Arms are tried top to bottom; the first fit wins.

Exercise: pattern_match.rs

Reproduce the output right, then trace which match arm wins for point (2, -3).