Text of rust.docs.kernel.org › next › core › mem › union.MaybeUninit.html as Styx crawled it on Nov 19, 2026. The page may have changed since. Only its words are kept, without pictures or layout, and only the first part of a long page.

Open the live page

MaybeUninit in core::mem - Rust

Skip to main content MaybeUninit core :: mem Union Maybe Uninit 1.36.0 · Source #[repr(transparent)] pub union MaybeUninit<T> { /* private fields */ } Expand description A wrapper type to construct uninitialized instances of T . § Initialization invariant The compiler, in general, assumes that a variable is properly initialized or “valid” according to the requirements of the variable’s type. For example, a variable of reference type must be aligned and non-null.

This is an invariant that must always be upheld, even in unsafe code. As a consequence, zero-initializing a variable of reference type causes instantaneous undefined behavior, no matter whether that reference ever gets used to access memory: use std::mem::{ self , MaybeUninit}; let x: & i32 = unsafe { mem::zeroed() }; // undefined behavior! ⚠️ // The equivalent code with `MaybeUninit<&i32>`: let x: & i32 = unsafe { MaybeUninit::zeroed().assume_init() }; // undefined behavior! ⚠️ This is exploited by the compiler for various optimizations, such as eliding run-time checks and optimizing enum layout.

Similarly, entirely uninitialized memory may have any content, while a bool must always be true or false . Hence, creating an uninitialized bool is undefined behavior: use std::mem::{ self , MaybeUninit}; let b: bool = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️ // The equivalent code with `MaybeUninit<bool>`: let b: bool = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️ Moreover, uninitialized memory is special in that it does not have a fixed value (“fixed” meaning “it won’t change without being written to”).

Reading the same uninitialized byte multiple times can give different results. This makes it undefined behavior to have uninitialized data in a variable even if that variable has an integer type, which otherwise can hold any fixed bit pattern: use std::mem::{ self , MaybeUninit}; let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior! ⚠️ // The equivalent code with `MaybeUninit<i32>`: let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! ⚠️ Conversely, sometimes it is okay to not initialize all bytes of a MaybeUninit before calling assume_init .

For instance, padding bytes do not have to be initialized. See the field-by-field struct initialization example below for a case of that. On top of that, remember that most types have additional invariants beyond merely being considered initialized at the type level. For example, a 1 -initialized Vec<T> is considered initialized (under the current implementation; this does not constitute a stable guarantee) because the only requirement the compiler knows about it is that the data pointer must be non-null.

Creating such a Vec<T> does not cause immediate undefined behavior, but will cause undefined behavior with most safe operations (including dropping it). § Examples MaybeUninit<T> serves to enable unsafe code to deal with uninitialized data. It is a signal to the compiler indicating that the data here might not be initialized: use std::mem::MaybeUninit; // Create an explicitly uninitialized reference. The compiler knows that data inside // a `MaybeUninit<T>` may be invalid, and hence this is not UB: let mut x = MaybeUninit::< & i32>::uninit(); // Set it to a valid value. x.write( & 0 ); // Extract the initialized data -- this is only allowed *after* properly // initializing `x`! let x = unsafe { x.assume_init() }; The compiler then knows to not make any incorrect assumptions or optimizations on this code.

You can think of MaybeUninit<T> as being a bit like Option<T> but without any of the run-time tracking and without any of the safety checks. § out-pointers You can use MaybeUninit<T> to implement “out-pointers”: instead of returning data from a function, pass it a pointer to some (uninitialized) memory to put the result into. This can be useful when it is important for the caller to control how the memory the result is stored in gets allocated, and you want to avoid unnecessary moves. use std::mem::MaybeUninit; unsafe fn make_vec(out: *mut Vec<i32>) { // `write` does not drop the old contents, which is important. unsafe { out.write( vec! [ 1 , 2 , 3 ]); } } let mut v = MaybeUninit::uninit(); unsafe { make_vec(v.as_mut_ptr()); } // Now we know `v` is initialized!

This also makes sure the vector gets // properly dropped. let v = unsafe { v.assume_init() }; assert_eq! ( & v, & [ 1 , 2 , 3 ]); § Initializing an array element-by-element MaybeUninit<T> can be used to initialize a large array element-by-element: use std::mem::{ self , MaybeUninit}; let data = { // Create an uninitialized array of `MaybeUninit`. let mut data: [MaybeUninit<Vec<u32>>; 1000 ] = [ const { MaybeUninit::uninit() }; 1000 ]; // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop, // we have a memory leak, but there is no memory safety issue. for elem in &mut data[..] { elem.write( vec! [ 42 ]); } // Everything is initialized.

Transmute the array to the // initialized type. unsafe { mem::transmute::< _ , [Vec<u32>; 1000 ]>(data) } }; assert_eq! ( & data[ 0 ], & [ 42 ]); You can also work with partially initialized arrays, which could be found in low-level datastructures. use std::mem::MaybeUninit; // Create an uninitialized array of `MaybeUninit`. let mut data: [MaybeUninit<String>; 1000 ] = [ const { MaybeUninit::uninit() }; 1000 ]; // Count the number of elements we have assigned. let mut data_len: usize = 0 ; for elem in &mut data[ 0 ..

500 ] { elem.write(String::from( "hello" )); data_len += 1 ; } // For each item in the array, drop if we allocated it. for elem in &mut data[ 0 ..data_len] { unsafe { elem.assume_init_drop(); } } § Initializing a struct field-by-field You can use MaybeUninit<T> and the &raw mut syntax to initialize structs field by field: use std::mem::MaybeUninit; #[derive(Debug, PartialEq)] pub struct Foo { name: String, list: Vec<u8>, } let foo = { let mut uninit: MaybeUninit<Foo> = MaybeUninit::uninit(); let ptr = uninit.as_mut_ptr(); // Initializing the `name` field // Using `write` instead of assignment via `=` to not call `drop` on the // old, uninitialized value. unsafe { ( & raw mut ( * ptr).name).write( "Bob" .to_string()); } // Initializing the `list` field // If there is a panic here, then the `String` in the `name` field leaks. unsafe { ( & raw mut ( * ptr).list).write( vec! [ 0 , 1 , 2 ]); } // All the fields are initialized, so we call `assume_init` to get an initialized Foo. unsafe { uninit.assume_init() } }; assert_eq! ( foo, Foo { name: "Bob" .to_string(), list: vec! [ 0 , 1 , 2 ] } ); Note that we have not initialized the padding, but that’s fine – it does not have to be initialized.

In fact, even if we had initialized the padding in uninit , those bytes would be lost when copying the result: no matter the contents of the padding bytes in uninit , they will always be uninitialized in foo . § Layout MaybeUninit<T> is guaranteed to have the same size, alignment, and ABI as T : use std::mem::MaybeUninit; assert_eq! (size_of::<MaybeUninit<u64>>(), size_of::<u64>()); assert_eq! (align_of::<MaybeUninit<u64>>(), align_of::<u64>()); However remember that a type containing a MaybeUninit<T> is not necessarily the same layout; Rust does not in general guarantee that the fields of a Foo<T> have the same order as a Foo<U> even if T and U have the same size and alignment.

Furthermore because any bit value is valid for a MaybeUninit<T> the compiler can’t apply non-zero/niche-filling optimizations, potentially resulting in a larger size: assert_eq! (size_of::< Option <bool>>(), 1 ); assert_eq! (size_of::< Option <MaybeUninit<bool>>>(), 2 ); If T is FFI-safe, then so is MaybeUninit<T> . While MaybeUninit is #[repr(transparent)] (indicating it guarantees the same size, alignment, and ABI as T ), this does not change any of the previous caveats.

Option<T> and Option<MaybeUninit<T>> may still have d

The rest of this page is on the live site.