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!("Negative 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: 0 matches the value zero.
  • OR Pattern (|): 1 | 3 | 5 matches if n is 1, 3, or 5.
  • Range Pattern (..=): 10..=20 matches integers from 10 to 20. Works for char too ('a'..='z').
  • Variable Binding: x in x if x < 0 binds the value of n if the guard condition holds.
  • Match Guard (if): The if x < 0 condition must be true for the arm to match.
  • Wildcard (_): Catches any remaining values, ensuring exhaustiveness.