Power of the `|` operator in pattern matching

697 points crb233

Found out that the | operator in match statements is more powerful than I thought, and I hadn't seen any documentation for this extended behavior. After searching, I did find it hiding in the Rust Reference. Essentially, | isn't a special syntax for match statements but actually a kind of operator used in all pattern matching contexts, including patterns nested within tuples and structs.

Take this example:

match value {
    Some(2 | 3 | 5 | 7) => println!("prime"),
    Some(0 | 1 | 4 | 9) => println!("square"),
    None => println!("nothing"),
    _ => println!("something else"),
}

which I would originally have written as:

match value {
    Some(2) | Some(3) | Some(5) | Some(7) => println!("prime"),
    Some(0) | Some(1) | Some(4) | Some(9) => println!("square"),
    None => println!("nothing"),
    _ => println!("something else"),
}

Using if-let:

if let Some("fn" | "let" | "if") = token {
    println!("keyword");
}

Multiple | operators try all possible combinations:

match vec {
    (0, 0) => println!("here"),
    (-1 | 0 | 1, -1 | 0 | 1) => println!("close"),
    _ => println!("far away"),
}

Anyway, thought that this might be useful for someone else too.