Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Smart Pointers and Memory

The std::mem module

Reference for Rust std::mem: swap, replace, take, drop, forget, size_of, align_of, size_of_val, discriminant, needs_drop and transmute, with examples.

std::mem collects small functions for working with values as blocks of memory: moving them around without breaking ownership rules (swap, replace, take), controlling when they are destroyed (drop, forget) and asking about their layout (size_of, align_of). Most of it is safe and used in everyday code, especially mem::take and mem::replace when you must move a value out of a &mut reference.

A few items (transmute, zeroed, forget misuse) are sharp tools. Wrapper types such as ManuallyDrop and MaybeUninit also live here.

Rust
use std::mem;

let mut a = String::from("old");
let previous = mem::replace(&mut a, String::from("new"));

Try it

Rust swap, replace and take

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 Sizes, drop and forget

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
pub fn swap<T>(x: &mut T, y: &mut T);
pub fn replace<T>(dest: &mut T, src: T) -> T;
pub fn take<T: Default>(dest: &mut T) -> T;
pub fn drop<T>(_x: T);
pub fn forget<T>(t: T);
pub const fn size_of<T>() -> usize;
pub const fn size_of_val<T: ?Sized>(val: &T) -> usize;
pub const fn align_of<T>() -> usize;
pub const fn needs_drop<T: ?Sized>() -> bool;
pub fn discriminant<T>(v: &T) -> Discriminant<T>;
pub const unsafe fn transmute<Src, Dst>(src: Src) -> Dst;
Function Description
swap(&mut a, &mut b) Exchanges two values in place without dropping either.
replace(&mut dest, src) Puts src in dest and returns the old value.
take(&mut dest) replace(dest, T::default()).
drop(x) Takes ownership and lets the value be dropped at once. It is an ordinary empty function (also in the prelude).
forget(x) Takes ownership and does not run the destructor. Leaking is safe, but resources are never released.
size_of::<T>() Size in bytes, a multiple of the alignment, 0 for zero-sized types.
align_of::<T>() Required alignment of T.
size_of_val(&v) Size of the actual value, valid for slices and dyn Trait.
discriminant(&e) Opaque tag you can compare to test whether two enum values are the same variant.
transmute Reinterprets bits; unsafe and extremely easy to misuse.

Edge cases. swap(&mut x, &mut x) cannot be written (two &mut to one place do not compile). Struct layout is unspecified for repr(Rust) types, so size_of may include padding and can change between compiler versions; do not hardcode it. Option<&T>, Option<Box<T>> and Option<NonNull<T>> are the same size as the pointer (niche optimization).

Usage notes

  • To move a field out of &mut self, use mem::take (if Default), mem::replace (any value) or Option::take. See Option take and replace.
  • mem::drop is how you end a MutexGuard or RefCell borrow early. It is not needed for plain integers (Copy types are not affected by moving).
  • mem::forget does not make a value safe to forget: leaking a JoinHandle or guard keeps the resource alive forever. Prefer ManuallyDrop when you need control.
  • mem::discriminant(&a) == mem::discriminant(&b) compares enum variants while ignoring payloads.
  • size_of is const, so it can size arrays: [u8; size_of::<u64>()].
  • mem::zeroed and mem::uninitialized are dangerous; use MaybeUninit. transmute between types of different size does not compile.