mem::swap, mem::replace, mem::take
pub fn swap<T>(x: &mut T, y: &mut T)
pub fn replace<T>(dest: &mut T, src: T) -> T
pub fn take<T>(dest: &mut T) -> T
where
T: DefaultExchange two values, or take a value out of a place by leaving something else behind.
| Parameter | Description |
|---|---|
x, y | The two mutable locations swapped in place. |
dest | The place to overwrite. replace and take both leave dest initialized. |
src | The value replace writes into dest. |
Returns: swap returns (). replace returns the previous contents of dest. take returns the previous contents and leaves Default::default() in dest.
- take is not a way to use a value after a move out of a non-Default type. If T has no Default, use replace with an explicit standby value, or restructure the code.
- These functions are safe. They do not transmute representations or unsafely invent values.
use std::mem;
fn main() {
let mut a = 1;
let mut b = 2;
mem::swap(&mut a, &mut b);
println!("swap={a} {b}");
let mut left = String::from("old");
let taken = mem::take(&mut left);
println!("take={taken} left={left:?}");
let mut current = String::from("old");
let previous = mem::replace(&mut current, String::from("new"));
println!("replace prev={previous} now={current}");
}Expected output
swap=2 1
take=old left=""
replace prev=old now=newRelated: Default, Clone, and Copy, Official std::mem