MaybeUninit for safe uninitialized memory
Marcus Chen
Jan 2026
1 tab
use std::mem::MaybeUninit;
fn main() {
let mut uninit: MaybeUninit<i32> = MaybeUninit::uninit();
unsafe {
uninit.as_mut_ptr().write(42);
let value = uninit.assume_init();
println!("Value: {}", value);
}
}
1 file · rust
Explain with highlit
MaybeUninit<T> is the safe way to work with uninitialized memory. It's useful for FFI, performance-critical code, or when you need to initialize large arrays element-by-element. Unlike uninitialized variables (which are UB), MaybeUninit is explicitly designed for this. You write to it via .as_mut_ptr() or .write(), then call .assume_init() once it's fully initialized. The assumption is your responsibility, so it's still unsafe, but it's safer than raw pointers. I use it for zero-copy deserialization or when initializing large fixed-size buffers. It's a low-level tool but essential for certain patterns where you can't afford the overhead of default initialization.