Match

See also: Reference – Match expressions

With the keyword, a value is pattern matched against several match arms. Each match arm consists of at least one pattern and an optional  guard. Individual patterns are separated with a vertical bar.

Example
Patterns can introduce variable bindings, which can be used in the expression of the match arm. If a match arm has multiple patterns, all patterns must have the same bindings with the same types:

guards
Each match arm can have an  guard with a condition that should be fulfilled:

Note that the  guard, if present, applies to all patterns in the same match arm. In the following example, the  guard is executed three times:

Rust processes match arms in consecutive order from top to bottom. It executes the first match arm where at least one pattern matches and the  guard, if present, returns. It always executes at most one match arm.

Exhaustiveness
blocks must be exhaustive: Every possible value of the matched type must be covered. For example, the following doesn't compile:

The reason why  blocks must be exhaustive, is that they are expressions and can return a value:

Trailing commas
The right side of a match arm, after the, must be an expression. The match arms are separated with commas. The comma after the last match arm is optional. The comma is also optional if the expression is a block expression, which includes:


 * regular blocks
 * unsafe blocks
 * loops
 * conditions (,, etc.)
 * match blocks
 * async blocks
 * try blocks (, these are still experimental)

How many match arms are executed?
Usually, exactly one  arm in a   expression is executed, but there are two exceptions:

  When matching on an enum with no variants or on the never type, there are no match arms, and the code is never executed:

  When an  guard panics or diverges, no match arm is executed:

 