Swap the values of two mutable references.
The std::mem::swap function swaps the values at two mutable references without requiring the type to implement Clone or Copy. It is useful for efficiently exchanging values without temporary variables.
swap works by performing a bitwise exchange of the memory underlying the two references. It runs in O(1) time proportional to the size of the type.
This function is commonly used in sorting algorithms, buffer rotation, and any situation where two values need to be exchanged in place.
| Name | Description | Optional |
|---|---|---|
x |
A mutable reference to the first value. | No |
y |
A mutable reference to the second value. | No |
use std::mem;
let mut a = 1;
let mut b = 2;
mem::swap(&mut a, &mut b);
assert_eq!(a, 2);
assert_eq!(b, 1);