21.7 Matching Literals, Variables, and Ranges
You can match:
- Literals: e.g.,
1
,"apple"
,false
. - Constants: Named constants or static items.
- Variables: Simple identifiers (match “anything,” binding it to the identifier).
- Ranges (
a..=b
): Integer or character ranges, e.g.,4..=10
.
fn classify_number(x: i32) { match x { 1 => println!("One"), 2 | 3 => println!("Two or three"), // OR patterns 4..=10 => println!("Between 4 and 10 inclusive"), _ => println!("Something else"), } } fn main() { classify_number(1); classify_number(3); classify_number(7); classify_number(50); }
21.7.1 Key Points
- Wildcard Pattern (
_
): Catches all unmatched cases. - OR Pattern (
|
): Any sub-pattern matching is enough to select that arm. - Ranges: Valid for integers or chars; floating-point ranges aren’t supported in patterns.