Skip to content

Can we guarantee that repr(rust) union fields live at offset 0? #595

Open

Description

@joshlf

Per The Rust Reference:

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.

Activity

  1. zachs18 commented on Dec 29, 2025

    @zachs18

    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

    1. with #[repr(C)] struct U8ThenBool { a: u8, b: bool } ↩

  2. RalfJung commented on Dec 29, 2025

    @RalfJung
    Member

    FWIW this is mostly a t-lang ask.

  3. added
    A-layoutTopic: Related to data structure layout (`#[repr]`)
    S-not-opsemDespite being in this repo, this is not primarily a T-opsem question
    on Dec 29, 2025
  4. added a commit that references this issue on Dec 30, 2025
  5. joshlf commented on Dec 30, 2025

    @joshlf
    Author

    Put up rust-lang/reference#2128 to stabilize the offset of fields in repr(C) unions.

  6. added a commit that references this issue on Jan 27, 2026
  7. added
    S-pending-designStatus: Resolving this issue requires addressing some open design questions
    and removed
    S-not-opsemDespite being in this repo, this is not primarily a T-opsem question
    on Jun 29, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-layoutTopic: Related to data structure layout (`#[repr]`)S-pending-designStatus: Resolving this issue requires addressing some open design questionsT-lang

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions