Bit flags in rust

Besides using bitflags - Rust , is there an idiomatic way to do bit flags in Rust ?

[[ EDIT: removed "via enums" ]]

I'm trying something like

pub enum TokenClass {
    Adv = 1,
    Verb = 2,
    Noun = 4,
    Conj = 8,
    Mark = 16,
    Asgn = 32,
    Lpar = 64,
}

impl TokenClass {
    const AVN: u32 = TokenClass::Adv | TokenClass::Verb | TokenClass::Noun;
}

and getting a "BitOr" not implemented on TokenClass error.

The idiomatic way is using the bitflags crate, that you already linked :slight_smile:

As you can see, Rust enums aren't great for implementing bitflags, since you will struggle to make them "closed". If you have Adv and Verb, you also need a variant for Adv | Verb combined, and so on..

1 Like

You can make a struct with an integer and overload the bitwise operations to work with the enum as you wanted. But now you're just reimplementing the crate.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.