A match guard refines a pattern with a boolean condition after the shape already matches.

Program

Play the program to choose a score and see which guarded arm classifies it.

score
match_guards.rs
Replay: real traced execution (multi-file project)
fn main() {
    let score = 82;
    let label = grade(score);
    println!("{score}:{label}");
}

fn grade(score: i32) -> &'static str {
    match score {
        n if n >= 90 => "excellent",
        n if n >= 60 => "pass",
        _ => "retry",
    }
}
fn main() {
    let score = 59;
    let label = grade(score);
    println!("{score}:{label}");
}

fn grade(score: i32) -> &'static str {
    match score {
        n if n >= 90 => "excellent",
        n if n >= 60 => "pass",
        _ => "retry",
    }
}
fn main() {
    let score = 95;
    let label = grade(score);
    println!("{score}:{label}");
}

fn grade(score: i32) -> &'static str {
    match score {
        n if n >= 90 => "excellent",
        n if n >= 60 => "pass",
        _ => "retry",
    }
}
  1. score ← 82

    1fn main() {2    let scor→ 82e = 82; //@score=82, 59, 953    let label = grade(scor82e);4    println!("{score}:{label}");
  2. label ← "pass"

    2    let score = 82; //@score=82, 59, 953    let labe→ "pass"l = grade(scor82e);4    println!("{score}:{label}");5}
    output82:pass
  1. score ← 59

    1fn main() {2    let scor→ 59e = 59;3    let label = grade(scor59e);4    println!("{score}:{label}");
  2. label ← "retry"

    2    let score = 59;3    let labe→ "retry"l = grade(scor59e);4    println!("{score}:{label}");5}
    output59:retry
  1. score ← 95

    1fn main() {2    let scor→ 95e = 95;3    let label = grade(scor95e);4    println!("{score}:{label}");
  2. label ← "excellent"

    2    let score = 95;3    let labe→ "excellent"l = grade(scor95e);4    println!("{score}:{label}");5}
    output95:excellent
guard `n if n >= 60` matches only when the value also passes the condition.
arm order The first matching guarded arm wins, so the excellent arm is checked before pass.
fallback `_` catches values that did not satisfy any earlier guard.