How can I swap elements in a vector, section, or array in Rust?

My code is as follows:

fn swap<T>(mut collection: Vec<T>, a: usize, b: usize) { let temp = collection[a]; collection[a] = collection[b]; collection[b] = temp; } 

Rust is pretty sure that I am not allowed to "switch from dereferencing" or "exit indexed content", whatever that is. How to convince Rust that this is possible?

+5
source share
2 answers

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 { // Can't take two mutable loans from one vector, so instead just cast // them to their raw pointers to do the swap let pa: *mut T = &mut self[a]; let pb: *mut T = &mut self[b]; ptr::swap(pa, pb); } } 

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.

+16
source

As mentioned in @ gsingh2011, the accepted answer is no longer a good approach. With current Rust, this code works fine:

 fn main() { let mut numbers = vec![1, 2, 3]; println!("before = {:?}", numbers); numbers.swap(0, 2); println!("after = {:?}", numbers); } 

try here

+2
source

Source: https://habr.com/ru/post/1201248/


All Articles