External Publication
Visit Post

For structs that have fields that have only one possible representation, enums should use that field as the discriminant

Rust Internals [Unofficial] June 7, 2026
Source
#[repr(u8)] #[derive(Clone, Copy)] enum FooDiscriminant { Disc = 0x01, } #[repr(u8)] #[derive(Clone, Copy)] enum BarDiscriminant { Disc = 0x02, } #[repr(C)] struct Foo { x: u8, y: u8, z: u8, disc: FooDiscriminant, } #[repr(C)] struct Bar { x: u8, y: u8, z: u8, disc: BarDiscriminant, } enum FooBar { Foo(Foo), Bar(Bar), } In this example, the disc field of both the Foo and Bar types are at the same offset. Both types have the same size and alignment. But contrary to what you might imagine the compiler might optimize this code into, it turns out that the size of FooBar is 5 instead of 4. But the compiler could easily see through the structure of these inner types and choose to use those fields for the discriminants, and as a result the size of FooBar would be 4.

Discussion in the ATmosphere

Loading comments...