I have a variable that consists of several flags ORed together, and I'd like to test which combination of them my value is and act on that. Unfortunately, the |
operator has a different meaning in a match
statement, so I can't write
match x {
(FLAG1 | FLAG2) => return 5;
(FLAG1 | FLAG3) => return 6;
(FLAG2 | FLAG3) => return y;
_ => return 0;
}
and instead I need to precompute (FLAG1 | FLAG2)
and so on, making my code ugly and unreadable. Is there a better way to do this?
The left part of each arm of a match
expression is a pattern not an expression. That means you can only do pattern matching there. You can't use operators, accessors and function calls.
Unfortunately, I think you might be stuck with doing an if..else
:
if x == FLAG1 | FLAG2 { return 5 }
else if x == FLAG1 | FLAG2 { return 6 }
else if x == FLAG1 | FLAG2 { return y }
else { return 0 };
But, since if..else
(and match
) are expressions, you can at least eliminate the repeated return
:
return if x == FLAG1 | FLAG2 { 5 }
else if x == FLAG1 | FLAG2 { 6 }
else if x == FLAG1 | FLAG2 { y }
else { 0 };
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