Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simpler way to bind the entire match when using multiple matches?

Tags:

Binding a variable to a match expression can be done by using @ and a variable name, like:

#[derive(Debug)]
enum Foo {
    First,
    Second,
    Third,
    Fourth,
}

fn bar(f: Foo) {
    match f {
        e @ Foo::First => println!("{:?}", e),
        _ => {}
    }
}

If you want to bind e to multiple matches, you have to repeat the binding on every possibility.

fn bar(f: Foo) {
    match f {
        e @ Foo::First | e @ Foo::Second | e @ Foo::Fourth => println!("{:?}", e),
        _ => {}
    }
}

Is there a simpler way of doing it?

like image 382
hellow Avatar asked Dec 13 '18 09:12

hellow


1 Answers

If you want to continue to use pattern matching, it isn't currently possible to avoid repeating the binding. However, once RFC 2535 gets implemented you will be able to nest 'OR' patterns like so:

fn bar(f: Foo) {
    match f {
        e @ (Foo::First | Foo::Second | Foo::Fourth) => println!("{:?}", e),
        _ => {}
    }
}

The tracking issue for the implementation is here: https://github.com/rust-lang/rust/issues/54883

like image 83
Joe Clay Avatar answered Nov 15 '22 06:11

Joe Clay