Pattern Matching
match selects an arm by the shape and value of its input. Patterns can bind payloads, destructure aggregates, classify integer intervals, and add boolean guards. Examples below are independent fragments unless a complete function is shown.
match is an expression
match returns a value, so it works naturally in assignments and returns.
let x = 5;
let label = match x {
0 => "zero",
1 | 2 => "small",
_ => "other",
};Common pattern forms
Wildcards and bindings
let value = 42;
let result = match value {
0 => 0,
n => n * 2,
};Tuples and nested tuples
A nested tuple pattern follows the same nesting as the value.
let pair = (0, -2);
let axis = match pair {
(0, y) => y,
(x, 0) => x,
(x, y) => x + y,
};
let nested = ((1, 2), 3);
let total = match nested {
((a, b), c) => a + b + c,
};Enums and payload extraction
A variant pattern names the constructor and binds its payload.
fn unwrapOrZero(opt: Option<i32>): i32 {
return match opt {
Some(v) => v,
None => 0,
};
}
fn describe(res: Result<i32, i32>): i32 {
return match res {
Ok(v) => v,
Err(code) => code,
};
}Struct patterns
Shorthand field patterns bind a field under its own name.
struct Point {
public:
x: f32,
y: f32,
}
fn distanceSquared(p: Point): f32 {
return match p {
Point { x, y } => x * x + y * y,
};
}Fixed-size array and slice-style patterns
let values = [1, 2, 3];
match values {
[a, b, c] => {
$println(a);
$println(b);
$println(c);
},
_ => {
$println("unexpected shape");
},
};Ranges, guards, and or-patterns
Or-patterns
let x = 2;
let kind = match x {
1 | 2 => "small",
3 => "three",
_ => "other",
};Range patterns
a..b excludes the upper endpoint; a..=b includes it.
let n = 9;
let digits = match n {
0..10 => "single digit",
10..=99 => "two digits",
_ => "large",
};Guards
Guards add a second condition after the pattern.
let x = 5;
let selected = match x {
n if n > 3 => n,
_ => 0,
};Ownership and exhaustiveness
A by-value match can transfer an owning payload into its selected arm. Matching a borrowed value keeps payload access borrowed; it does not create an owner that can outlive the original. Choose a borrowed parameter when the caller needs to retain the matched value.
Account for every possible variant or add an intentional fallback. A guarded arm can fail even after its pattern matches, so preserve an unguarded path for remaining cases. Alternatives joined with | must provide consistent bindings used by the arm.
Tuple, struct, and array patterns also work in let bindings. A tuple spells its full shape with _ for ignored positions; an array rest is terminal (.. to ignore, ...rest to bind). For enum mismatch and early return, use match or if let. See Advanced Patterns.
Best Practices
- Prefer
matchwhen you need exhaustive branching and value extraction in one place. - Use guards for extra conditions instead of encoding too much logic into the pattern itself.
- Make payload ownership explicit at the function boundary and keep patterns close to the actual data shape.