7

Take a typical check for bit-flags:

if      (v & (1 << 0)) != 0 { foo(); }
else if (v & (1 << 1)) != 0 { bar(); }
else if (v & (1 << 2)) != 0 { baz(); }

How would this be written as a match statement?

ideasman42
  • 42,413
  • 44
  • 197
  • 320

1 Answers1

13
if      (v & (1 << 0)) != 0 { foo(); }
else if (v & (1 << 1)) != 0 { bar(); }
else if (v & (1 << 2)) != 0 { baz(); }

Such concrete code can be rewritten like this:

match v.trailing_zeros() {
    0 => foo(),
    1 => bar(),
    2 => baz(),
    _ => {},
}
fghj
  • 8,898
  • 4
  • 28
  • 56
  • 1
    That's really clever! I wrote some tests to check that this is indeed correct (and they pass): https://play.rust-lang.org/?gist=bcbd5fb07635e0601747abf06b8d3f57&version=stable&backtrace=0 – Dogbert Aug 27 '16 at 09:48
  • 1
    Is the generated code as efficient as a bitmask check? – ideasman42 Aug 29 '19 at 13:41