How to get mutable references to two array elements at the same time?
fn change(a: &mut i32, b: &mut i32) {
let c = *a;
*a = *b;
*b = c;
}
fn main() {
let mut v = vec![1, 2, 3];
change(&mut v[0], &mut v[1]);
}
When I compile the code above, it has the error:
error[E0499]: cannot borrow `v` as mutable more than once at a time
--> src/main.rs:9:32
|
9 | change(&mut v[0], &mut v[1]);
| - ^ - first borrow ends here
| | |
| | second mutable borrow occurs here
| first mutable borrow occurs here
Why does the compiler prohibit it? v[0]
and v[1]
occupy different memory positions, so it's not dangerous to use these together. And what should I do if I come across this problem?
Answers
The error you're encountering is due to Rust's borrowing rules, which prevent you from borrowing mutable references to the same data simultaneously. In your code, you're trying to borrow v
mutably twice, once for &mut v[0]
and once for &mut v[1]
. This violates the rule that you can't have multiple mutable borrows to the same data at the same time.
Even though v[0]
and v[1]
are different elements in the vector, the compiler can't guarantee that they don't overlap in memory. This is because vectors are stored as contiguous arrays in memory, so modifying one element could potentially affect the memory layout of adjacent elements.
To fix this issue, you can create two separate mutable references to the vector and then pass them to the change
function:
fn change(a: &mut i32, b: &mut i32) {
let c = *a;
*a = *b;
*b = c;
}
fn main() {
let mut v = vec![1, 2, 3];
// Create mutable references to the vector elements
let (first, second) = v.split_at_mut(2);
let first = &mut first[0];
let second = &mut second[0];
// Call the change function with the mutable references
change(first, second);
}
In this code, split_at_mut(2)
is used to split the vector into two mutable slices at index 2. Then, separate mutable references to the first and second elements are obtained from each slice. Finally, these mutable references are passed to the change
function.