match
match compares a value, the subject, against a list of patterns and runs the first arm whose pattern fits. It is both a statement and an expression.
match = "match" subject "{" [ arm { "," arm } [ "," ] ] "}"
arm = pattern { "|" pattern } [ "if" expression ] "=>" body
| "_" "=>" body
body = expression | block | "return" [expression] | "throw" expression
| "break" [label] | "continue" [label]
match status {
200 => PrintLine("OK"),
404 => PrintLine("Not Found"),
_ => PrintLine("Unknown")
}
Arms
Each arm is a pattern, =>, and a body. A comma separates arms and may follow the last one; an arm whose body is a block may leave it out. The same arm grammar serves match, the catch arms of error handling, and the compile-time when.
The arms are tried from the top, and the first whose pattern fits — and whose guard, if it has one, is true — is the one that runs. No other arm runs, and nothing falls through.
_ is the default arm. It takes every value the arms before it leave, so it must be the last arm and takes no guard:
error: the default arm must be the last match arm
error: the default arm '_' cannot have a guard
else => is not an arm: it is error: 'else' is not a match arm, with help: use '_' for the default arm. _ is the same wildcard inside a larger pattern, as in .Some(_).
An arm covered entirely by earlier unguarded arms can never run, and is refused: error: match arm is unreachable because an earlier pattern matches every value. A _ arm is never reported this way — it covers whatever remains, possibly nothing. Two arms with the same pattern are refused too: error: duplicate pattern in match.
Alternatives
a | b joins alternatives in one arm: it is taken when any of them fits, tried in source order. Alternatives may nest inside a payload, as in .Digit(0 | 1), and a guard after them covers all of them:
func Family(os: OperatingSystem) -> int32 {
return match os {
.FreeBSD | .Linux | .macOS => 1i32,
_ => 2i32,
};
}
An alternative binds no names — error: pattern alternative cannot bind 'value' — so an arm that needs a binding is written on its own. Coverage counts what the alternatives match together, so true | false covers a bool.
The subject
The subject is any expression and is evaluated exactly once, before the first arm is tried. Like a condition, it ends at the first { that could open the arms, so a structure literal subject is parenthesised: match (Point { x: 0, y: 0 }) { … }.
A temporary subject, or one handed over with match move value { … }, belongs to the match: arms that bind its parts own them, and an arm that binds nothing destroys it. A named subject that is plain data is matched as a copy, which leaves the original with its owner; a named subject that owns resources is matched with match move value, or as a clone with match value.Clone(). A borrowed subject is matched in place, and its bindings alias the parts where they lie — see Copy and move.
Arm bodies
| Body | Use |
|---|---|
| an expression | the arm's value, or a call run for its effect |
a block { … } | several statements; in a value, its last value |
return, throw, break, continue | leave the function, handler or loop from this arm |
match Direction::East {
.North => {
effect = 1;
},
.East => {
effect = 2;
},
_ => {}
}
Statement and expression
A match at the start of a statement is a statement: its arms run for their effect, and it produces no value. A block arm of a statement may end with a call that returns nothing without its ;, and a block arm ending in any other value is an error whose help reads add ';' or use the value. Anywhere else — after =, after return, as an argument — a match is an expression, and every arm produces the match's value. A block arm then yields the expression it ends with, written without a ;:
let label = match status {
200 => "OK",
404 => "Not Found",
_ => "Unknown"
};
let size = match kind {
.Small => 1,
.Large => {
let base = Measure();
base * 2
},
};
The arms of a match expression must agree on a type, as the branches of an if value do:
error: match arm type mismatch: expected 'int', found '()'
An arm that leaves — return, throw, break, continue, or a call that never returns, such as Panic — produces no value and does not take part. Where the context fixes the type, such as an annotated binding or a return, every arm takes it: an unsuffixed literal in an arm must fit it, a none or .Some(…) arm is completed by it, a plain arm converts to an optional or a sum as an initializer would, and a .Case written without its type names a case of it. With no such type, the first arm whose type is complete decides. See Optionals and Sum types.
A match at the start of a statement ends at its }, so an operator written after it does not apply to its value. To use the value there, bind it, or wrap the match in parentheses.
Exhaustiveness
Every match, statement or expression, covers every value of its subject:
| Subject | Covered by |
|---|---|
| an enum | an arm per member |
| a variant | an arm per case |
| an optional or a sum | every level: none and present, and each member |
bool | true and false |
| a tuple | every combination of its elements |
| an integer, a floating-point number, a character, a slice | _, or an arm that binds every value |
| a structure | an arm whose field patterns all match anything, or _ |
A statement that means to ignore the values it does not name says so with _ => {}, so turning a statement into an expression never changes what it must cover. A missing case is reported by name:
error: match on 'Mode' is not exhaustive; missing Mode::Small
error: match on 'bool8' is not exhaustive; missing false
error: match on '(bool8, bool8)' is not exhaustive; missing (true, false)
error: match on 'DigitError | RangeError' is not exhaustive; missing _: RangeError
error: match on 'int32' is not exhaustive; its arms do not cover every value
help: add a '_' arm
Three rules make coverage predictable:
- A guarded arm covers nothing, because its guard might be
false.true => …, false if ready => …still lacks an unguardedfalse. - Ranges and literals never replace
_for a number or a character, even when they happen to reach every value. - A case is covered by its arms together:
.Light(true)and.Light(false)cover aLight(bool)case without a.Light(_)arm, while literals of an integer payload never cover theirs.
_ is allowed on an enum or variant too, but it is a promise made on behalf of cases that do not exist yet: add a case later, and every match that names its cases one by one stops compiling at the spot that needs a decision, while one ending in _ quietly gives the new case the default answer.
Converting an integer to an enum with as is unchecked, so it can produce a value that is no member at all. An exhaustive match without a _ arm that meets such a value stops the program with Panic: no match arm matched value of 'Month', instead of taking an arm or falling through.
See also
- Patterns — every pattern an arm can use
- Variants — matching cases and their payloads
- Sums — matching members of a sum
- Conditional —
ifas a value - Learn: Match, Match expression, Exhaustive
return
The return statement: returning a value or nothing, the check that every path returns, moving a value out, and return inside expressions.
Patterns
Every pattern form — literals, ranges, bindings, _, tuples, structures, enum and variant cases, typed patterns, none and .Some — alternatives and guards.