21.7 Matching Literals, Variables, and Ranges

You can match:

  • Literals: 1, true, "apple", etc.
  • Constant Values: Named constants or static items.
  • Variables: Simple identifiers.
  • Ranges (a..=b): Integer or character ranges, for example 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 cases not matched earlier.
  • OR Pattern |: Matches if any sub-pattern matches.
  • Ranges: Allowed for numeric or character types but not floating-point.