Skip to content

Normal enums vs flags

Blokyk edited this page May 8, 2023 · 1 revision

We could have a mechanism where, by default, enums behave like any other type; no "int to any enum" type of stuff, and no bitwise operations. This would also mean that we could have more confidence in exhaustiveness analysis for pattern matching. It guarantees there'd be no surprises when working with enum values. From an implementation POV, it also gives us more flexibility in how we represent enums.

However, if you actually want the int<->enum equivalence, or want to use an enum as a more ergonomic flag/bitmask, then you could simply declare your intentions upfront, which would relax the rules a bit, and prevent us from emitting warnings about non-exhaustive patterns where it might not be relevant. We could also then provide bitwise operations, specialized ways for checking flags, etc...

One important limitation to flags though is that you can't "inherit" from them, since that obviously wouldn't make any sense, and would be incompatible with the underlying numeric representation.

This could either be achieved through some kind of marker attribute, or with a different kind:

#[Flag]
enum Permission { Read, Write, Create, Delete }
// vs
flag Permission { Read = 0, Write, Create, Delete }