21.11 OR Patterns and Combined Guards
Use the |
operator to combine multiple patterns into a single match arm:
fn check_char(c: char) { match c { 'a' | 'A' => println!("Found an 'a'!"), _ => println!("Not an 'a'"), } } fn main() { check_char('A'); check_char('z'); }
You can also mix guards with OR patterns:
fn main() { let x = 4; let b = false; match x { // Matches if x is 4, 5, or 6, AND b == true 4 | 5 | 6 if b => println!("yes"), _ => println!("no"), } }
The guard (if b
) applies only after the pattern itself matches one of 4
, 5
, or 6
.