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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With