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.
use std::mem; let mut a = String::from("old"); let previous = mem::replace(&mut a, String::from("new"));
Try it
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.
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
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, usemem::take(ifDefault),mem::replace(any value) orOption::take. See Option take and replace. mem::dropis how you end aMutexGuardorRefCellborrow early. It is not needed for plain integers (Copytypes are not affected by moving).mem::forgetdoes not make a value safe to forget: leaking aJoinHandleor guard keeps the resource alive forever. PreferManuallyDropwhen you need control.mem::discriminant(&a) == mem::discriminant(&b)compares enum variants while ignoring payloads.size_ofisconst, so it can size arrays:[u8; size_of::<u64>()].mem::zeroedandmem::uninitializedare dangerous; useMaybeUninit.transmutebetween types of different size does not compile.