match Deep Dive
Patterns and guards.
The match Expression
match compares a value against a series of patterns and runs the arm of the first match. It is an expression, so it returns a value.
fn main() {
let n = 3;
let label = match n {
1 => "one",
2 => "two",
3 => "three",
_ => "many",
};
println!("{label}");
}Exhaustiveness
A match must cover every possible value. The wildcard _ catches anything not matched by earlier arms, ensuring exhaustiveness.
fn main() {
let x = 42;
match x {
0 => println!("zero"),
_ => println!("nonzero"),
}
}All lessons in this course
- match Deep Dive
- if let and while let
- Binding with @
- Destructuring