@@ -23,12 +23,8 @@ use std::mem::{self, MaybeUninit};
2323const SIZE : usize = 10 ;
2424
2525let x = {
26- // Create an uninitialized array of `MaybeUninit`. The `assume_init` is
27- // safe because the type we are claiming to have initialized here is a
28- // bunch of `MaybeUninit`s, which do not require initialization.
29- let mut x : [MaybeUninit <Box <u32 >>; SIZE ] = unsafe {
30- MaybeUninit :: uninit (). assume_init ()
31- };
26+ // Create an uninitialized array of `MaybeUninit`.
27+ let mut x = [const { MaybeUninit :: uninit () }; SIZE ];
3228
3329 // Dropping a `MaybeUninit` does nothing. Thus using raw pointer
3430 // assignment instead of `ptr::write` does not cause the old
@@ -48,14 +44,7 @@ println!("{x:?}");
4844
4945This code proceeds in three steps:
5046
51- 1 . Create an array of ` MaybeUninit<T> ` . With current stable Rust, we have to use
52- unsafe code for this: we take some uninitialized piece of memory
53- (` MaybeUninit::uninit() ` ) and claim we have fully initialized it
54- ([ ` assume_init() ` ] [ assume_init ] ). This seems ridiculous, because we didn't!
55- The reason this is correct is that the array consists itself entirely of
56- ` MaybeUninit ` , which do not actually require initialization. For most other
57- types, doing ` MaybeUninit::uninit().assume_init() ` produces an invalid
58- instance of said type, so you got yourself some Undefined Behavior.
47+ 1 . Create an array of ` MaybeUninit<T> ` .
5948
60492 . Initialize the array. The subtle aspect of this is that usually, when we use
6150 ` = ` to assign to a value that the Rust type checker considers to already be
@@ -165,7 +154,6 @@ anywhere expects to be handed uninitialized memory, so if you're going to pass
165154it around at all, be sure to be * really* careful.
166155
167156[ `MaybeUninit` ] : ../core/mem/union.MaybeUninit.html
168- [ assume_init ] : ../core/mem/union.MaybeUninit.html#method.assume_init
169157[ `ptr` ] : ../core/ptr/index.html
170158[ raw_reference ] : ../reference/types/pointer.html#r-type.pointer.raw.constructor
171159[ `write` ] : ../core/ptr/fn.write.html
0 commit comments