std::mem helpers for low-level memory manipulation

Marcus Chen Jan 2026
1 tab
use std::mem;

fn main() {
    let mut x = 5;
    let mut y = 10;

    mem::swap(&mut x, &mut y);
    println!("x: {}, y: {}", x, y);

    let old = mem::replace(&mut x, 42);
    println!("old: {}, new: {}", old, x);
}
1 file · rust Explain with highlit

The std::mem module provides utilities for working with memory: size_of, align_of, swap, replace, take, drop, forget, and transmute. I use mem::swap to exchange values without cloning, mem::replace to take a value out of a mutable reference, and mem::take for Default types. mem::drop explicitly drops a value early, and mem::forget prevents drop (leaks). mem::transmute reinterprets bytes (extremely unsafe, avoid when possible). These functions are building blocks for unsafe code and performance optimizations. For example, mem::replace(&mut self.data, Vec::new()) takes ownership without cloning. Understanding std::mem is key to writing efficient Rust.