Swap the values at two mutable locations of the same type, without deinitialising or copying either one.
use std::mem; let x = &mut 5; let y = &mut 42; mem::swap(x, y); assert_eq!(42, *x); assert_eq!(5, *y);
(From offical Rust doc)
How can two values be swapped without copying? How did the value 42
go from y
to x
? This shouldn't be possible.
The function does actually make a copy internally: here is its source extracted from the documentation:
pub fn swap<T>(x: &mut T, y: &mut T) {
unsafe {
// Give ourselves some scratch space to work with
let mut t: T = uninitialized();
// Perform the swap, `&mut` pointers never alias
ptr::copy_nonoverlapping(&*x, &mut t, 1);
ptr::copy_nonoverlapping(&*y, x, 1);
ptr::copy_nonoverlapping(&t, y, 1);
// y and t now point to the same thing,
// but we need to completely forget `t`
// because it's no longer relevant.
forget(t);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With