How to declare typed bitflags in Rust?

后端 未结 4 2117
-上瘾入骨i
-上瘾入骨i 2021-01-26 05:48

It\'s possible to declare flags in Rust - similar to how it would be done in C.

pub const FOO: u32 = (1 << 0);
pub const BAR: u32 = (1 << 1);

let fl         


        
4条回答
  •  刺人心
    刺人心 (楼主)
    2021-01-26 06:11

    You should know that type creates a type alias in Rust, not a new type, so you MyFlag and MyOtherFlag have the same type.

    If these flags are named but not indexed, and they are not too numerous, then you could just stick a bunch of bool types into a struct.

    #[repr(packed)]
    struct MyFlags {
        a: bool,
        b: bool
    }
    

    In fact, each bool requires a u8 even with #[repr(packed)]. I donno if that originates with supporting references to individual bools, but they take a u8 without #[repr(packed)] too, so not sure. I'd think an RFC or issue could be filed about that though give 1240. If wasting a u8 per flag like this works, then it's likely syntax compatible with bitfields whenever they land.

    If you need indexing into the flags, then you'd need some messy or fancy solution in C too.

    If you want bitfields with values larger than bool, there are a variety of ways to hack this together along the lines of the previous two comments. And some bitfield crates. You'll find several more discussed in the Rust RFC discussion threads 314 and 1449 on adding bitfield support to Rust. In this case, I'd do it however you like for now, but maybe plan on switching it to bitfields whenever they eventually land.

提交回复
热议问题