macro_rules! bitflag_match {
($operation:expr, {
$($t:tt)*
}) => { ... };
}
Expand description
A macro that matches flags values, similar to Rust’s match
statement.
In a regular match
statement, the syntax Flag::A | Flag::B
is interpreted as an or-pattern,
instead of the bitwise-or of Flag::A
and Flag::B
. This can be surprising when combined with flags types
because Flag::A | Flag::B
won’t match the pattern Flag::A | Flag::B
. This macro is an alternative to
match
for flags values that doesn’t have this issue.
§Syntax
bitflag_match!(expression, {
pattern1 => result1,
pattern2 => result2,
..
_ => default_result,
})
The final _ => default_result
arm is required, otherwise the macro will fail to compile.
§Examples
use bitflag_attr::{bitflag, bitflag_match};
#[bitflag(u8)]
#[derive(Clone, Copy, PartialEq)]
enum Flags {
A = 1 << 0,
B = 1 << 1,
C = 1 << 2,
}
let flags = Flags::A | Flags::B;
bitflag_match!(flags, {
Flags::A | Flags::B => println!("A and/or B are set"),
_ => println!("neither A nor B are set"),
})
§How it works
The macro expands to a series of if
statements, checking equality between the input expression
and each pattern. This allows for correct matching of bitflag combinations, which is not possible
with a regular match expression due to the way bitflags are implemented.
Patterns are evaluated in order.