match
| Arms with => | |
| Bind values | |
| Guards | |
| Exhaustiveness |
Arms with =>
Each arm pairs a pattern with an arrow and a result. The first pattern that fits wins and the rest are skipped:
let n = 2;
let text = match n {
1 => "one",
2 => "two",
_ => "many",
};
Bind values
Patterns can bind inner data to new names. Matching an Option shows Some value binding and None handling:
let opt = Some(7);
let v = match opt {
Some(x) => x,
None => 0,
};
Guards
A guard adds an extra if test to one arm. The arm matches only when both the pattern and the guard hold:
let n = 10;
let label = match n {
x if x > 100 => "huge",
_ => "small",
};
Exhaustiveness
Match must cover every possible value. A final underscore arm catches all leftovers and keeps the compiler satisfied:
let day = 3;
let kind = match day {
6 => "weekend",
7 => "weekend",
_ => "weekday",
};
Next: Loops
Article author: Arthur Isaev