Match expressions
A match expression is used for pattern matching, it allows you to match a value against a set of patterns and execute code based on the matching pattern.
1. Syntax
A match expression starts with the keyword match
followed by an expression and a list of arms.
Each arm begins with a pattern which is followed by the ⇒
operator, an
expression, and a comma.
A block expression is typically used if the logic in the arm is more
than a single expression.
The pattern in a given arm may introduce variables that can be used in
expression of the said arm.
If the pattern contains variables that are unused in the expression, then the wildcard _
can be
used in their place.
2. Semantics
A match expression is evaluated by evaluating the expression and then matching the value against the patterns in the arms in order. The first arm whose pattern matches the value of the expression is executed and the result of the expression in the arm is returned as the result of the match.
3. Limitations
Currently two kinds of match expression are supported:
Match on an Enum.
match enum_var {
variant_0(a, b, c) => { /* code */ }
variant_1(_) => { /* code */ }
...
variant_k(a, c) => { /* code */ }
}
Where enum_var
is an instance of some enum and variant_0
are all the variants of the said enum, order in the way that they were declared., `variant_1
, …,
`variant_k