Pattern matching compares a value with structural patterns and runs the first matching arm. Rust requires every possible situation to be covered, so the compiler can catch missing cases. section 3.2.2 section 5.2.1
Build a match expression from these parts:
- Write match followed by the value and a brace-delimited list of arms. section 3.2.2
- Put a pattern on the left of => and the action or result on the right; separate arms with commas. section 3.2.2
- Use _ as a wildcard for any remaining case. section 3.2.2
- Remember that matching stops at the first matching arm, even when later arms would also match. section 3.2.2
Matching a number
A match can produce a value as well as perform an action: let my_number = 5; let second_number = match my_number { 0 => 0, 5 => 10, _ => 2, }; Every arm must produce a compatible type. Returning an integer from one arm and a string from another produces a compiler error. section 3.2.2
Matching structure and conditions
Patterns can describe tuples, bind values, and add conditions. For example, matching (sky, temperature) can distinguish ("cloudy", "warm"), while a match guard such as if children == 0 adds a condition to an arm. Option uses the same idea: Some(number) extracts a value, while None handles its absence. section 3.2.2 section 5.2.1
fn main() {
let my_number: u8 = 5;
match my_number {
0 => println!("it's zero"),
1 => println!("it's one"),
2 => println!("it's two"),
}
}
A minimal non-exhaustive match makes the compiler's coverage requirement concrete; adding a wildcard completes the cases. section 3.2.2











