bitflags generates flags enums with well-defined semantics and ergonomic end-user APIs.
You can use bitflags to:
- provide more user-friendly bindings to C APIs where flags may or may not be fully known in advance.
- generate efficient options types with string parsing and formatting support.
You can't use bitflags to:
guarantee only bits corresponding to defined flags will ever be set.
bitflagsallows access to the underlying bits type so arbitrary bits may be set.define bitfields.
bitflagsonly generates types where set bits denote the presence of some combination of flags.
Add this to your Cargo.toml:
[dependencies]
bitflags = "2.13.1"and this to your source code:
use bitflags::bitflags;Generate a flags structure:
use bitflags::bitflags;// The `bitflags!` macro generates `struct`s that manage a set of flags.bitflags!{/// Represents a set of flags. #[derive(Debug,Clone,Copy,PartialEq,Eq,PartialOrd,Ord,Hash)]structFlags:u32{/// The value `A`, at bit position `0`.constA = 0b00000001;/// The value `B`, at bit position `1`.constB = 0b00000010;/// The value `C`, at bit position `2`.constC = 0b00000100;/// The combination of `A`, `B`, and `C`.constABC = Self::A.bits() | Self::B.bits() | Self::C.bits();}}fnmain(){let e1 = Flags::A | Flags::C;let e2 = Flags::B | Flags::C;assert_eq!((e1 | e2),Flags::ABC);// unionassert_eq!((e1 & e2),Flags::C);// intersectionassert_eq!((e1 - e2),Flags::A);// set differenceassert_eq!(!e2,Flags::A);// set complement}The bitflags library defines a few Cargo features that you can opt-in to:
std: Implement theErrortrait on error types used bybitflags.serde: Support derivingserdetraits on generated flags types.arbitrary: Support derivingarbitrarytraits on generated flags types.bytemuck: Support derivingbytemucktraits on generated flags types.
Also see bitflags_derive for other flags-aware traits.
The minimum supported Rust version is documented in the Cargo.toml file.
This may be bumped in minor releases as necessary.