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.

All the arms that don’t break the control flow must evaluate to the same type. An arm breaks the control flow if it returns or panics.

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, `variant_1, …​, `variant_k are all the variants of the said enum, order in the way that they were declared.

Match on an felt252.

match felt_var {
    0 => { /* code */ }
    _ => { /* code */ }
}

Where felt_var is a felt252 and the match patterns are the literal '0' and wildcard '_' (which matches any value).