0
0
Rustprogramming~5 mins

Matching multiple patterns in Rust

Choose your learning style9 modes available
Introduction

Matching multiple patterns lets you check if a value fits any of several options in one place. It keeps your code clean and easy to read.

When you want to run the same code for different possible values.
When you have a list of options that should be handled the same way.
When you want to simplify long if-else chains checking many values.
When you want to group similar cases in a match statement.
When you want to avoid repeating code for each similar pattern.
Syntax
Rust
match value {
    pattern1 | pattern2 | pattern3 => {
        // code for any of these patterns
    },
    _ => {
        // code for other cases
    }
}

You use the pipe symbol | to separate multiple patterns.

All patterns separated by | share the same code block.

Examples
This matches if x is 1, 2, or 3 and prints the same message.
Rust
let x = 3;
match x {
    1 | 2 | 3 => println!("x is 1, 2, or 3"),
    _ => println!("x is something else"),
}
This matches vowels and prints "vowel" for any of them.
Rust
let c = 'a';
match c {
    'a' | 'e' | 'i' | 'o' | 'u' => println!("vowel"),
    _ => println!("consonant"),
}
Sample Program

This program checks the number for a day of the week. It prints if it's a weekday or weekend using multiple patterns.

Rust
fn main() {
    let day = 6;
    match day {
        1 | 2 | 3 | 4 | 5 => println!("It's a weekday."),
        6 | 7 => println!("It's the weekend!"),
        _ => println!("Not a valid day."),
    }
}
OutputSuccess
Important Notes

You can mix literal values and variables in patterns when matching multiple options.

Using | helps avoid repeating the same code for similar cases.

Summary

Use | to match multiple patterns in one match arm.

This keeps your code shorter and easier to understand.

It works well for grouping similar cases together.