There is a swap method defined for &mut [T] . Since a Vec<T> can be mutually dereferenced as &mut [T] , this method can be called directly:
fn main() { let mut numbers = vec![1, 2, 3]; println!("before = {:?}", numbers); numbers.swap(0, 2); println!("after = {:?}", numbers); }
To implement this yourself, you need to write unsafe code. Vec::swap implemented as follows:
fn swap(&mut self, a: usize, b: usize) { unsafe {
It takes two raw pointers from a vector and uses ptr::swap to safely replace them.
There is also mem::swap(&mut T, &mut T) when you need to swap two different variables. This cannot be used here because Rust will not allow you to take two mutable borrowings from the same vector.
Arjan source share