Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitwise or in match?

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?

like image 785
Jakob Weisblat Avatar asked Sep 04 '18 18:09

Jakob Weisblat


1 Answers

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 };
like image 118
Peter Hall Avatar answered Oct 04 '22 13:10

Peter Hall