std::mem helpers for low-level memory manipulation

1256
0

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.