1

Does the compiler behave differently with MaybeUninit or with a union with the same structure? If yes, what additional things does it do with MaybeUninit?

Specifically, is it the same (except for the different methods) to use original MaybeUninit:

#[repr(transparent)]
pub union MaybeUninit<T> {
    uninit: (),
    value: ManuallyDrop<T>,
}

or to use:

#[repr(transparent)]
pub union AnotherUninit<T> {
    uninit: (),
    value: ManuallyDrop<T>,
}
FreD
  • 393
  • 2
  • 12

1 Answers1

2

MaybeUninit is not treated specifically by the compiler (it is a lang item, but because the compiler needs to refer to it, not because it is treated specifically).

However, #[repr(transparent)] on unions is unstable, and as explained in MaybeUninit's docs:

Over time, the exact guarantees of #[repr(transparent)] on unions may evolve, and MaybeUninit may or may not remain #[repr(transparent)]. That said, MaybeUninit<T> will always guarantee that it has the same size, alignment, and ABI as T; it’s just that the way MaybeUninit implements that guarantee may evolve.

Other than that, I don't think there is a difference between std's MaybeUninit and a homemade one.

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77