Nyx by Example

Match Guards

Match guards add an extra boolean condition to a match arm using the if keyword. An arm only fires when both its pattern matches and its guard evaluates to true, enabling fine-grained branching that would otherwise require nested if-else chains.

Code

// Match guards: condiciones adicionales dentro de los brazos del match

fn classify(n: int) -> String {
    return match n {
        x if x > 100  => "muy grande (" + int_to_string(x) + ")",
        x if x > 10   => "grande (" + int_to_string(x) + ")",
        x if x > 0    => "positivo (" + int_to_string(x) + ")",
        x if x == 0   => "cero",
        x if x > -10  => "negativo pequeno (" + int_to_string(x) + ")",
        x              => "muy negativo (" + int_to_string(x) + ")"
    }
}

fn grade(score: int) -> String {
    return match score {
        s if s >= 90 => "A",
        s if s >= 80 => "B",
        s if s >= 70 => "C",
        s if s >= 60 => "D",
        _            => "F"
    }
}

fn main() -> int {
    print(classify(200))
    print(classify(50))
    print(classify(5))
    print(classify(0))
    print(classify(-3))
    print(classify(-99))

    print("nota 95: " + grade(95))
    print("nota 82: " + grade(82))
    print("nota 71: " + grade(71))
    print("nota 55: " + grade(55))

    return 0
}

Output

muy grande (200)
grande (50)
positivo (5)
cero
negativo pequeno (-3)
muy negativo (-99)
nota 95: A
nota 82: B
nota 71: C
nota 55: F

Explanation

Each arm in the classify match uses the wildcard pattern x to bind the scrutinee, then applies an if guard to restrict when the arm fires. Arms are evaluated top-to-bottom, so the ordering matters: x > 100 must appear before x > 10, otherwise values like 200 would be caught by the less specific guard first. The final arm has no guard, making it an unconditional catch-all that ensures exhaustiveness.

The grade function shows the same technique applied to an academic grading scale. The wildcard _ in the last arm is equivalent to a catch-all variable pattern but discards the value, signaling to readers that the bound value is intentionally unused. Both functions return a String expression directly from the match, so no intermediate variable is needed.

Match guards are especially powerful when combined with enum variants that carry data — you can first check which variant you have, then apply a numeric or string condition on its payload, all within a single concise match block.

← Previous Next →

Source: examples/by-example/28-match-guard.nx