How enumflags2 works
masterCore Concept
enumflags2 implements a bitflags data structure by annotating an enum with the #[bitflags] attribute.
Key Distinction: Unlike other bitflags crates, enumflags2 maintains a strict type-level distinction between a single flag (the enum type itself, e.g., Test) and a set of flags (the BitFlags<T> type, e.g., BitFlags<Test>). This distinction allows you to use idiomatic Rust patterns like match and iter on the flags.
Key Features:
- Automatic Bit Assignment: If you don't specify a bit value for an enum variant,
enumflags2automatically picks an unused bit. - Compile-time Safety: It detects incorrect bitflag configurations at compile time.
- Opaque Types: You do not interact with generated types directly; you work exclusively with
struct BitFlags<Enum>;. - Rich Debugging: The
Debugformatter prints both the binary value and the enum variants (e.g.,BitFlags(0b1111, [A, B, C, D])).
use enumflags2::{bitflags, BitFlags};
#[bitflags]
#[repr(u8)]
#[derive(Copy, Clone, Debug, PartialEq)]
enum Test {
A = 0b0001,
B = 0b0010,
C, // Automatically picks an unused bit
D = 0b1000,
}
// A set of flags is a BitFlags<Test>
let flags: BitFlags<Test> = Test::A | Test::B;