Skip to content

Accessing union field inside unsafe function requires extra unsafe block #53193

Closed
@gnzlbg

Description

@gnzlbg

Playground

Is this by design?

pub unsafe fn foo() -> u8 {
    union U {
        v: u8,
        c: u8,
    }
    // const C: u8 = unsafe { U { v: 0 }.c }; // OK
    const C: u8 = U { v: 0 }.c; // ERROR
    C
}

it produces:

error[E0133]: access to union field is unsafe and requires unsafe function or block
 --> src/main.rs:9:19
  |
9 |     const C: u8 = U { v: 0 }.c;
  |                   ^^^^^^^^^^^^ access to union field
  |
  = note: the field may not be properly initialized: using uninitialized data will cause undefined behavior

Wrapping the access in an unsafe block compiles, but since the function is already unsafe, that feels a bit redundant.

In non-unsafe functions one doesn't need to open two unsafe blocks to perform union field access unsafe { unsafe { ...union access... } } :D Is this doubly-unsafe ? :D

cc @oli-obk @RalfJung @eddyb

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions