Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Smart Pointers and Memory

Rust ManuallyDrop and MaybeUninit

Reference for Rust ManuallyDrop<T> and MaybeUninit<T>: suppress automatic drops, build values piece by piece, assume_init rules and safe array initialization.

Rust normally guarantees that every value is initialized and is dropped exactly once. Two wrapper types let unsafe code take control of those two guarantees. ManuallyDrop<T> stops the compiler from running T's destructor automatically; you decide if and when it runs. MaybeUninit<T> holds memory that may not yet contain a valid T, so you can fill it in gradually.

Both are tools for low-level code: containers, FFI, performance-sensitive initialization. Using them correctly requires unsafe at exactly the points where you promise something the compiler cannot check.

Rust
use std::mem::{ManuallyDrop, MaybeUninit};

let keep = ManuallyDrop::new(String::from("never dropped automatically"));
let slot: MaybeUninit<u32> = MaybeUninit::uninit();

Try it

Rust ManuallyDrop controls the destructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Filling an array with MaybeUninit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
#[repr(transparent)]
pub struct ManuallyDrop<T: ?Sized> { /* private */ }
impl<T> ManuallyDrop<T> {
    pub const fn new(value: T) -> ManuallyDrop<T>;
    pub const fn into_inner(slot: ManuallyDrop<T>) -> T;
    pub unsafe fn take(slot: &mut ManuallyDrop<T>) -> T;
}
impl<T: ?Sized> ManuallyDrop<T> {
    pub unsafe fn drop(slot: &mut ManuallyDrop<T>);
}

#[repr(transparent)]
pub union MaybeUninit<T> { /* private */ }
impl<T> MaybeUninit<T> {
    pub const fn uninit() -> MaybeUninit<T>;
    pub const fn zeroed() -> MaybeUninit<T>;
    pub const fn new(val: T) -> MaybeUninit<T>;
    pub fn write(&mut self, val: T) -> &mut T;
    pub const fn as_ptr(&self) -> *const T;
    pub const fn as_mut_ptr(&mut self) -> *mut T;
    pub const unsafe fn assume_init(self) -> T;
    pub const unsafe fn assume_init_ref(&self) -> &T;
    pub unsafe fn assume_init_drop(&mut self);
}
Item Description
ManuallyDrop::new / into_inner Wrap a value without a destructor / unwrap it (destructor active again).
ManuallyDrop::drop Runs the destructor in place. Unsafe: calling it twice, or using the value afterwards, is undefined behavior.
ManuallyDrop::take Moves the value out, leaving the wrapper logically empty. Unsafe: do not touch the wrapper afterwards.
MaybeUninit::uninit() Memory with no valid value.
MaybeUninit::zeroed() All bytes zero; valid only if T allows an all-zero pattern.
write(v) Safe: stores v and returns a reference to it. Does not drop old contents.
assume_init() Unsafe: you promise the memory holds a valid T.
assume_init_drop() Unsafe: runs T's destructor in place.

Edge cases. Dropping a MaybeUninit<T> never drops the T inside, so an initialized String that you forget to take out is leaked (safe but wasteful). Reading uninitialized bytes as an integer is undefined behavior, even for u8. Types such as bool, references, Box, NonZero* and enums have invalid bit patterns that zeroed or partial init can produce.

Usage notes

  • Prefer safe alternatives first: std::array::from_fn, Vec::with_capacity, Option<T>, or mem::take. Reach for MaybeUninit only when profiling or FFI demands it.
  • The old mem::uninitialized() and mem::zeroed() shortcuts are deprecated or dangerous; MaybeUninit replaced them.
  • ManuallyDrop is how Vec, Rc and friends hand out their parts without a double drop, and how mem::forget is conceptually implemented. See mem::forget on std::mem.
  • Wrapping a field in ManuallyDrop in a Drop impl lets you move it out in drop, which is otherwise forbidden.
  • Panic safety matters: if initialization code can panic halfway, make sure the partly built value is not dropped as if complete.
  • Pass as_mut_ptr() to C functions that fill an out-parameter, then call assume_init only after checking the return code.