You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Can we guarantee that repr(rust) union fields live at offset 0? #595
The memory layout of a union is undefined by default (in particular, fields do not have to be at offset 0), but the #[repr(...)] attribute can be used to fix a layout.
Would anyone be opposed to at least guaranteeing that union fields always live at offset 0? It would be helpful for zerocopy.
Update: It seems that The Rust Reference doesn't even guarantee this for repr(C) unions – their size is equal to the maximum size of any field, but offset for any non-maximally-sized-field is not guaranteed.
If we end up with validity guarantees that allow unions to have niches, then defining that repr(Rust) unions' fields always start at offset 0 would preclude the compiler from laying out union Foo { x: U8ThenBool, y: bool }1 with a niche by laying out y at offset 1 to overlap with x.b (CC #494 and #438 about the validity guarantees of unions).
That said, I would not be opposed to guaranteeing that #[repr(Rust)] unions have all fields at offset 0, and making this hypothetical optimization require a different, new repr (or just be impossible), as it seems of limited utility.
Footnotes
with #[repr(C)] struct U8ThenBool { a: u8, b: bool }↩
Activity
zachs18 commentedon Dec 29, 2025
If we end up with validity guarantees that allow unions to have niches, then defining that
repr(Rust)unions' fields always start at offset 0 would preclude the compiler from laying outunion Foo { x: U8ThenBool, y: bool }1 with a niche by laying outyat offset 1 to overlap withx.b(CC #494 and #438 about the validity guarantees of unions).That said, I would not be opposed to guaranteeing that
#[repr(Rust)]unions have all fields at offset 0, and making this hypothetical optimization require a different, newrepr(or just be impossible), as it seems of limited utility.Footnotes
with
#[repr(C)] struct U8ThenBool { a: u8, b: bool }↩RalfJung commentedon Dec 29, 2025
FWIW this is mostly a t-lang ask.
Guarantee `repr(C)` union field offset
joshlf commentedon Dec 30, 2025
Put up rust-lang/reference#2128 to stabilize the offset of fields in
repr(C)unions.Guarantee `repr(C)` union field offset