I want to swap elements of slice data
using library function, but it doesn't work because of multiple borrowing:
use std::mem;
fn example() {
let mut data = [1, 2, 3];
let i = 0;
let j = 1;
mem::swap(&mut data[i], &mut data[j]);
}
error[E0499]: cannot borrow `data[_]` as mutable more than once at a time
--> src/lib.rs:8:29
|
8 | mem::swap(&mut data[i], &mut data[j]);
| --------- ------------ ^^^^^^^^^^^^ second mutable borrow occurs here
| | |
| | first mutable borrow occurs here
| first borrow later used by call
|
It could be done manually, but I don't think using this code every time is great:
let temp = data[i];
data[i] = data[j];
data[j] = temp;
Is there any other solution to swap elements in slices?
Copy
types - otherwise it will result in a "cannot move out of indexed content". – Immersionism