21.7 Matching Literals, Ranges, Variables, and OR Patterns
Patterns can match specific values, ranges, or combine possibilities:
fn describe_number(n: i32) {
match n {
0 => println!("Zero"),
1 | 3 | 5 => println!("Small odd number (1, 3, or 5)"), // OR pattern `|`
10..=20 => println!("Between 10 and 20 (inclusive)"), // Range pattern `..=`
x if x < 0 => println!("Neg. number: {}", x), // Variable binding + Guard `if`
_ => println!("Other positive number"), // Wildcard `_`
}
}
fn main() {
describe_number(0); // Output: Zero
describe_number(3); // Output: Small odd number (1, 3, or 5)
describe_number(15); // Output: Between 10 and 20 (inclusive)
describe_number(-5); // Output: Negative number: -5
describe_number(100); // Output: Other positive number
}
- Literals:
0matches the value zero. - OR Pattern (
|):1 | 3 | 5matches ifnis 1, 3, or 5. - Range Pattern (
..=):10..=20matches integers from 10 to 20. Works forchartoo ('a'..='z'). - Variable Binding:
xinx if x < 0binds the value ofnif the guard condition holds. - Match Guard (
if): Theif x < 0condition must be true for the arm to match. - Wildcard (
_): Catches any remaining values, ensuring exhaustiveness.