Netwave
Netwave

Reputation: 42708

How to multibind or patterns in match expressions?

Is there a way of binding to the same name a bunch of or matchings?

So for example in the following code, I would like n to be any of the or matchs, 1, 2 or 3.

fn main() {
    match 2 {
        n @ 1 | 2 | 3 => {
            println!("{}", n);
        }
        _ => {},
    }
}

Playground

It complains with:

error[E0408]: variable `n` is not bound in all patterns
 --> src/main.rs:3:17
  |
3 |         n @ 1 | 2 | 3 => {
  |         -       ^   ^ pattern doesn't bind `n`
  |         |       |
  |         |       pattern doesn't bind `n`
  |         variable not in all patterns

Upvotes: 7

Views: 219

Answers (1)

Netwave
Netwave

Reputation: 42708

Just surrounding the or match with () (parenthesis) makes the binding properly:

fn main() {
    match 2 {
        n @ (1 | 2 | 3) => {
            println!("{}", n);
        }
        _ => {},
    }
}

Playground

Upvotes: 9

Related Questions