Question
Safely treating a `&[T]` as a `&[MaybeUninit<T>]` in Rust
How can/should I obtain a &[MaybeUninit<T>]
from a &[T]
?
Intuitively, I should be allowed to treat initialized memory as being possibly uninitialized, but intuition and unsafe
do not always mix well... Since MaybeUninit<T>
is guaranteed to have the same size and alignment as T
, it should be safe to transmute
a &[T]
into a &[MaybeUninit<T>]
?
Then again, the current implementation of MaybeUninit::new(val)
does more than just transmuting, it adds a ManuallyDrop::new(val)
wrapper. Does this mean that if I implemented slice_as_maybeuninit
via transmuting, I'd run into problems with destructors not being run? Which is not unsafe
, but still undesirable enough to restrict such a function to slices of data that implement Copy
(i.e., which do not implement Drop
).
To make my question(s) more precise:
- How should I implement
fn slice_as_maybeuninit<'a, T>(s: &'a [T]) -> &'a [MaybeUninit<T>]
, if at all? - How should I implement
fn slice_as_maybeuninit<'a, T: Copy>(s: &'a [T]) -> &'a [MaybeUninit<T>]
? // note theT: Copy
bound - Bonus: Why does
std::mem::MaybeUninit
not provide these operations for me?