RRust By Example
intermediatePatterns

Or Patterns

Match multiple patterns with | operator.

Or Patterns

Match multiple patterns with | operator.

Difficulty

Intermediate

Code

rust
fn main() {
    let x = 4;

    match x {
        1 | 2 => println!("one or two"),
        3..=5 => println!("three to five"),
        _ => println!("other"),
    }

    let c = 'z';
    match c {
        'a'..='j' => println!("early letter"),
        'k'..='z' => println!("late letter"),
        _ => println!("not a letter"),
    }

    // or with bindings
    let msg = Some(42);
    match msg {
        Some(n @ 1..=10) | Some(n @ 90..=100) => println!("special: {}", n),
        Some(n) => println!("normal: {}", n),
        None => println!("none"),
    }
}

Explanation

The | operator matches multiple patterns.

Key Concepts

  • Read the code carefully and understand the data flow
  • Try modifying the example to see how it changes behavior
  • Run this code in the Rust Playground

Related Topics

Browse more examples in the patterns category to build a complete understanding of this topic.

More Patterns Examples