What MaybeUninit is for

MaybeUninit<T> is a wrapper around raw storage for T that does not require the bytes to be initialized. This is useful when:

  • building arrays or buffers incrementally,
  • constructing large values in place,
  • interfacing with C APIs that write into caller-provided memory,
  • avoiding unnecessary default initialization for performance.

It is not a general replacement for Option<T> or Vec<T>. If your value is already fully initialized and may be absent, Option<T> is usually the better choice. MaybeUninit is specifically for memory that is not yet a valid Rust value.

Key rule

A MaybeUninit<T> can exist in any bit pattern, but you must only convert it into T after fully initializing it with a valid value.


Why not just use MaybeUninit everywhere?

Because it removes safety guarantees until you restore them manually. That means the burden shifts to you:

  • you must initialize every field before reading it,
  • you must avoid dropping uninitialized data,
  • you must handle panics during partial initialization carefully,
  • you must not assume the bytes represent a valid T until they really do.

Use it when the benefit is concrete. Otherwise, prefer safe abstractions.

Common use cases

ScenarioWhy MaybeUninit helps
Large arraysAvoids initializing every element twice
FFI output buffersLets C write directly into Rust-owned storage
Complex structsEnables in-place construction without temporaries
Performance-critical codeReduces redundant default construction

Creating uninitialized storage

The simplest form is:

use std::mem::MaybeUninit;

let x: MaybeUninit<u32> = MaybeUninit::uninit();

At this point, x does not contain a valid u32. You cannot safely call methods that assume initialization.

To write a value into it:

use std::mem::MaybeUninit;

let mut x: MaybeUninit<u32> = MaybeUninit::uninit();
x.write(42);

write stores the value into the underlying memory and returns a mutable reference to the written value. This is the preferred way to initialize a MaybeUninit<T>.

To read it back after initialization:

use std::mem::MaybeUninit;

let mut x: MaybeUninit<u32> = MaybeUninit::uninit();
x.write(42);

let value = unsafe { x.assume_init() };
assert_eq!(value, 42);

The unsafe is required because Rust cannot verify that you really initialized it correctly.


Initializing arrays element by element

A classic use case is building an array without first creating a default value for every slot. This matters when T is expensive to construct or does not implement Default.

Here is a safe pattern for fixed-size arrays:

use std::mem::MaybeUninit;

fn build_array() -> [String; 3] {
    let mut data: [MaybeUninit<String>; 3] = MaybeUninit::uninit_array();

    data[0].write("alpha".to_string());
    data[1].write("beta".to_string());
    data[2].write("gamma".to_string());

    unsafe { MaybeUninit::array_assume_init(data) }
}

This works because each element is initialized exactly once before conversion.

Why this pattern matters

If you wrote [String::new(), String::new(), String::new()] and then overwrote the elements, you would pay for unnecessary allocations and drops. MaybeUninit lets you construct only what you need.


Handling partial initialization safely

The tricky part is failure. Suppose you are building a collection and one element construction panics or returns an error. If you have already initialized some elements, you must clean them up manually.

A common pattern is to track how many elements have been initialized so far:

use std::mem::MaybeUninit;

fn build_strings(inputs: &[&str]) -> Result<Vec<String>, ()> {
    let mut data: Vec<MaybeUninit<String>> = Vec::with_capacity(inputs.len());
    unsafe { data.set_len(inputs.len()); }

    let mut initialized = 0;

    for (i, input) in inputs.iter().enumerate() {
        if input.is_empty() {
            for j in 0..initialized {
                unsafe { data[j].assume_init_drop(); }
            }
            return Err(());
        }

        data[i].write(input.to_string());
        initialized += 1;
    }

    let result = unsafe {
        let ptr = data.as_mut_ptr() as *mut String;
        let len = data.len();
        let cap = data.capacity();
        std::mem::forget(data);
        Vec::from_raw_parts(ptr, len, cap)
    };

    Ok(result)
}

This example shows the general idea, but in real code you should prefer safer helpers or encapsulate the pattern carefully. The important point is that partial initialization requires explicit cleanup logic.

Best practice

When building complex structures manually, isolate the unsafe code in a small, well-tested module. Expose a safe API on top of it.


In-place construction for FFI

MaybeUninit is especially useful when calling foreign functions that write into a caller-provided output parameter.

For example, imagine a C API that fills a struct:

#[repr(C)]
struct CPoint {
    x: i32,
    y: i32,
}

extern "C" {
    fn get_point(out: *mut CPoint);
}

fn read_point() -> CPoint {
    let mut point = std::mem::MaybeUninit::<CPoint>::uninit();

    unsafe {
        get_point(point.as_mut_ptr());
        point.assume_init()
    }
}

This pattern avoids creating a dummy CPoint before the foreign function overwrites it.

Important FFI rules

  • Only use MaybeUninit with FFI functions that fully initialize the output.
  • Ensure the C side writes a valid representation for the Rust type.
  • Use #[repr(C)] for shared data structures.
  • Never read from the buffer before the foreign function completes.

assume_init, assume_init_ref, and assume_init_mut

MaybeUninit offers several ways to extract initialized data:

  • assume_init() consumes the wrapper and returns T
  • assume_init_ref() returns &T
  • assume_init_mut() returns &mut T

Use the one that matches your ownership model.

use std::mem::MaybeUninit;

let mut value = MaybeUninit::new(99u32);

let r: &u32 = unsafe { value.assume_init_ref() };
assert_eq!(*r, 99);

let m: &mut u32 = unsafe { value.assume_init_mut() };
*m = 100;

let final_value = unsafe { value.assume_init() };
assert_eq!(final_value, 100);

These methods are unsafe because they trust you to guarantee initialization.


A practical pattern: building a cache entry in place

Suppose you are implementing a cache that stores parsed records. Parsing may fail, and the record may be large enough that you want to avoid temporary allocations.

A good design is to parse into local variables, then write the final value once:

use std::mem::MaybeUninit;

struct Record {
    id: u64,
    name: String,
    active: bool,
}

fn parse_record(input: &str) -> Result<Record, &'static str> {
    let mut out = MaybeUninit::<Record>::uninit();

    let parts: Vec<&str> = input.split(',').collect();
    if parts.len() != 3 {
        return Err("invalid format");
    }

    let id = parts[0].parse::<u64>().map_err(|_| "bad id")?;
    let name = parts[1].to_string();
    let active = match parts[2] {
        "true" => true,
        "false" => false,
        _ => return Err("bad flag"),
    };

    out.write(Record { id, name, active });
    Ok(unsafe { out.assume_init() })
}

In this example, MaybeUninit is not strictly necessary, but it illustrates a useful principle: only commit to the final storage once all validation has succeeded. In many cases, a plain Record { ... } is enough; use MaybeUninit when you need to avoid intermediate initialization or when the destination storage already exists.


When MaybeUninit is the wrong tool

MaybeUninit is powerful, but it is easy to overuse. Consider alternatives first.

NeedBetter choice
Optional presenceOption<T>
Lazy one-time initializationOnceLock<T> or OnceCell<T>
Shared mutable stateMutex<T> or RwLock<T>
Temporary replacementstd::mem::take or std::mem::replace
Raw untyped bytes[u8; N] or Vec<u8>

If you are not explicitly dealing with uninitialized storage, MaybeUninit is probably unnecessary.


Safety checklist

Before using MaybeUninit, verify these points:

  1. Every element or field is initialized exactly once.
  2. No code reads the value before initialization completes.
  3. Partial initialization paths clean up already-initialized values.
  4. The final value satisfies all invariants of T.
  5. Any FFI writes are guaranteed to produce a valid T.
  6. Unsafe blocks are small and documented.

A useful habit is to write a comment above each unsafe block explaining the invariant you rely on. That makes future maintenance much safer.


Summary

std::mem::MaybeUninit is Rust’s low-level escape hatch for uninitialized storage. It is most valuable when you need to:

  • construct values in place,
  • initialize arrays or buffers incrementally,
  • interface with APIs that write into caller-owned memory,
  • avoid unnecessary default initialization in hot paths.

The tradeoff is that you must manually uphold initialization and drop safety. Keep the unsafe surface area small, prefer higher-level abstractions when possible, and use MaybeUninit only when it clearly improves correctness or performance.

Learn more with useful resources