问题
In the standard library, the documentation shows how to instantiate arrays of
MaybeUninit
s:
let arr: [MaybeUninit<T>; N] =
MaybeUninit::uninit().assume_init();
We know this is safe because the contract of MaybeUninit
allows for uninitialized values. Next we are asked to use ptr::write(value)
to initialize each element. But this requires unsafe
code once again. We also know that overwriting a MaybeUninit
is safe, because it doesn't drop
anything. So why not just overwrite it like arr[i] = MaybeUninit::new(value)
?
回答1:
let arr: [MaybeUninit<T>; N] = MaybeUninit::uninit().assume_init();
is just a shortcut.
arr[i] = MaybeUninit::new(value)
, in your example arr[i]
is a MaybeUninit
so your question is just about what style to use to mutate a vector. You could also do arr[i].write(value)
that doesn't really change in practice but it's require nightly that why the doc don't use it. But you are right arr[i] = MaybeUninit::new(value)
allow to override the value too without unsafe keyword and it's a perfectly defined behavior.
The thing you forget is that MaybeUninit
is not really here to be used only inside Rust except very few case, Rust don't need it. We mostly use it when we dealing with ffi, so the exemple is not really a real word use case. So it can look strange. Here the author probably want to emulate a real word case where the array would be init outside Rust by using a raw pointer.
来源:https://stackoverflow.com/questions/56997322/why-use-ptrwrite-with-arrays-of-maybeuninits