How to Use MaybeUninit for Uninitialized Memory in Rust

Use MaybeUninit to allocate uninitialized memory, write data into it, and safely assume initialization before use.

Use std::mem::MaybeUninit<T> to allocate memory without initializing it, then write data into it and convert it to T only after initialization is complete.

use std::mem::MaybeUninit;

fn main() {
    let mut slot: MaybeUninit<i32> = MaybeUninit::uninit();
    slot.write(42);
    let value = unsafe { slot.assume_init() };
    println!("{value}");
}

This pattern avoids running the destructor for T during allocation, which is essential for types that cannot be default-initialized or when implementing custom allocators like TypedArena.