🌵

bitflagsを用いたRustの簡単なフラグ管理メモ

2024/05/13に公開


スクラップにメモしていたシリーズです。bitflagsクレートで複数のboolフラグを取り扱う方法を調べた結果のメモです。[bitflags "2.5.0"]

前提

Cargo.toml
[dependencies]
bitflags = "2.5.0"

サンプルコード

use bitflags::bitflags;

fn main() {
    bitflags! {
        #[derive(Debug, Default)]
        struct Fruits: u8 {
            const APPLE  = 0b00000001;
            const BANANA = 0b00000010;
            const CHERRY = 0b00000100;
        }
    }

    let mut fav = Fruits::default();
    println!("{:?}", fav); // Fruits(0x0)
    fav.insert(Fruits::all());
    println!("{:?}", fav); // Fruits(APPLE | BANANA | CHERRY)
    fav = fav & (Fruits::APPLE | Fruits::BANANA);
    println!("{:?}", fav); // Fruits(APPLE | BANANA)
    fav = fav - Fruits::BANANA;
    println!("{:?}", fav); // Fruits(APPLE)
    fav = !fav;
    println!("{:?}", fav); // Fruits(BANANA | CHERRY)
    for (name, fruit) in fav.iter_names() {
        println!("{}, {:?}", name, fruit);
        // BANANA, Fruits(BANANA)
        // CHERRY, Fruits(CHERRY)
    }
    println!("{}", fav.bits()); // 6
    assert!(fav.contains(Fruits::BANANA));
    assert!(fav.intersects(Fruits::APPLE | Fruits::BANANA));
    fav.remove(Fruits::all());
    println!("{:?}", fav); // Fruits(0x0)
    assert!(fav.is_empty());
    assert!((!fav).is_all());
}

参考文献

Discussion