Pattern matching

match is an expression; its arms cover literals, tuples, structs, enums, ranges, slices, regex, string prefixes, or-patterns, and guards.

Summary

match returns the value of the matched arm. A guard clause (n if cond) adds a runtime condition on top of a pattern. The @ operator captures and tests simultaneously: n @ 1..=10 binds n and requires it to be in range. Slice patterns ([first, ..rest]) destructure arrays. The semantic analyzer verifies exhaustiveness: every match must have a wildcard or cover all variants.

Canonical

match is an expression: it returns the value of the matched arm.

let result = match value {
    0 => "zero"
    1 => "one"
    n if n > 100 => "big: {n}"  -- guard clause
    _ => "other"                 -- wildcard
}

Pattern Types

-- literals
match data {
    42       => "exact int"
    "hello"  => "exact string"
    true     => "boolean"
    null     => "null"
    _        => "wildcard"
}

-- variable binding (captures the value)
match data {
    x => "bound: {x}"
}

-- tuple destructuring
match point {
    (0, 0) => "origin"
    (x, 0) => "on x-axis at {x}"
    (0, y) => "on y-axis at {y}"
    (x, y) => "({x}, {y})"
}

-- struct destructuring
match shape {
    Circle { radius } => "circle r={radius}"
    Rect { w, h }     => "rect {w}x{h}"
}

-- enum destructuring
match result {
    Ok(val)   => "success: {val}"
    Err(msg)  => "error: {msg}"
}

-- or patterns
match ch {
    "a" | "e" | "i" | "o" | "u" => "vowel"
    _ => "consonant"
}

-- range patterns
match age {
    0..18   => "minor"
    18..=65 => "adult"
    _       => "senior"
}

-- slice patterns (arrays)
match arr {
    [first, ..rest] => "head: {first}, rest: {rest}"
    []              => "empty"
}

-- @ capture (bind and test simultaneously)
match value {
    n @ 1..=10 => "small: {n}"
    n          => "other: {n}"
}

-- regex patterns
match input {
    /^[0-9]+$/ => "number"
    /^[a-z]+$/ => "word"
    _          => "other"
}

-- string prefix patterns
match url {
    "https://" ++ rest => "secure: {rest}"
    "http://" ++ rest  => "insecure: {rest}"
    _                  => "unknown protocol"
}

The semantic analyzer checks that match covers all cases. A wildcard _ or variable pattern makes a match exhaustive. For enum matches, the checker verifies all variants are covered.