Reputation: 9815
I have such code that can't be compiled:
fn my_cool_replace<T: Copy>(arr: &mut [T]) {
swap(&mut arr[2], &mut arr[5]);
}
fn swap<T: Copy>(a: &mut T, b: &mut T) {
let c: T = *a;
*a = *b;
*b = c;
}
The error is:
error[E0499]: cannot borrow `arr[_]` as mutable more than once at a time
I want the function my_cool_replace
to replace 2-th and 5-th elements in the given mutable slice of an array or a vector. Why do I have such error and what is the best way to fix it?
Upvotes: 1
Views: 283
Reputation: 3758
As already correctly stated, you can't do this in one swoop ─ but:
fn my_cool_replace<T: Copy>(arr: &mut [T]) {
let mut tmp = arr[5];
tmp = std::mem::replace(&mut arr[2], tmp);
_ = std::mem::replace(&mut arr[5], tmp);
}
Upvotes: 0
Reputation: 8390
From the Rust Book:
Here are the rules for borrowing in Rust:
First, any borrow must last for a scope no greater than that of the owner. Second, you may have one or the other of these two kinds of borrows, but not both at the same time:
- one or more references (&T) to a resource,
- exactly one mutable reference (&mut T).
Your swap
function smells weird by accepting references as arguments. Instead, it could have been rewritten to accept a mutable reference to an array and the indices the user like to swap:
fn swap<T: Copy>(arr: &mut [T], p1: usize, p2: usize) {
let tmp = arr[p1];
arr[p1] = arr[p2];
arr[p2] = tmp;
}
Upvotes: 3