3 ms·
#[repr(C)] #[derive(PartialEq, Eq, Clone, Copy)] struct Foo(i32); const FOO_BAR: Foo = Foo(0); const FOO_BAZ: Foo = Foo(1); I remember writing
by gpm 8y ago
#[repr(C)]
#[derive(PartialEq, Eq, Clone, Copy)]
struct Foo(i32);
const FOO_BAR: Foo = Foo(0);
const FOO_BAZ: Foo = Foo(1);
I remember writing a macro to handle this properly, even using modules for namespacing, ages ago...
- huntie 8y agoYou can also use associated consts which feels nicer in my opinion: #[repr(C)] #[derive(PartialEq, Eq, Clone, Copy)] struct Foo(i32); impl Foo { const BAR: Foo = Foo(0); const BAZ: Foo = Foo(1); }
- v_lisivka 8y agoIt doesn't play nicely with tooling like debugging output(#[derive(Debug)]), introspection, serialization, match statements, etc. My solution to this problem, for i8/u8 enum's only, is just to list of unused values as enum Foo { ..., RESERVED_2=2, RESERVED_3=3,.. RESERVED_255=255,}.
- gpm 8y agoThese days it would be perfectly possible to have a macro that looked like cenum! { Foo: i32, Bar = 1, Baz = 2 } That expanded to the above `struct Foo(i32)` code and implemented Debug printing `Foo::Bar`, `Foo::Baz`, and `Foo::Unknown(3)` or something.
- v_lisivka 8y agoOf course, we can use i32 directly, but when project has hundreds of enum's, when enum's are constantly updated, when different crates are using different incompatible approaches to represent repr(C) enum's, it hurts. Rust compiler can pack Option<NonZeroU8> into single byte, so it can do that for repr(C) enum's with e.g. `Other(2..255:u8),` variant too (see my proposition above). Technically, they are not different, just have more specific cases.