# Bit flags in rust

**URL:** <https://users.rust-lang.org/t/bit-flags-in-rust/41142>\
**Category:** uncategorized\
**Created:** [April 17, 2020, 9:08pm UTC](https://users.rust-lang.org/t/bit-flags-in-rust/41142 "2020-04-17T21:08:36Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![anon80458984](https://avatars.discourse-cdn.com/v4/letter/a/53a042/32.png) [@anon80458984](https://users.rust-lang.org/u/anon80458984)\
**Post date:** [April 17, 2020, 9:08pm UTC](https://users.rust-lang.org/t/bit-flags-in-rust/41142/1 "2020-04-17T21:08:36Z")

</div>

Besides using [bitflags - Rust](https://docs.rs/bitflags/1.2.1/bitflags/) , is there an idiomatic way to do bit flags in Rust ?

[[EDIT: removed "via enums"]]

I'm trying something like

```rust
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.

---

<div class="post-metadata">

**Author:** ![bluss](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/bluss/32/4051_2.png) [@bluss](https://users.rust-lang.org/u/bluss)\
**Post date:** [April 17, 2020, 9:20pm UTC](https://users.rust-lang.org/t/bit-flags-in-rust/41142/2 "2020-04-17T21:20:16Z")

</div>

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

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..

---

<div class="post-metadata">

**Author:** ![alice](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/alice/32/9777_2.png) [@alice](https://users.rust-lang.org/u/alice)\
**Post date:** [April 17, 2020, 9:57pm UTC](https://users.rust-lang.org/t/bit-flags-in-rust/41142/3 "2020-04-17T21:57:03Z")

</div>

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.

---

<div class="post-metadata">

**Author:** ![system](https://sea1.discourse-cdn.com/flex019/user_avatar/users.rust-lang.org/system/32/51372_2.png) [@system](https://users.rust-lang.org/u/system)\
**Post date:** [July 16, 2020, 9:57pm UTC](https://users.rust-lang.org/t/bit-flags-in-rust/41142/4 "2020-07-16T21:57:17Z")

</div>

Closed on July 16, 2020, 9:57pm UTC

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