Let's say I want to swap the first and third items of a vector using a bit-twiddling hack:
fn main() {
let mut v = vec![0, 1, 2, 3, 4, 5, 6, 7];
{
let first_item = &mut v[0];
let third_item = &mut v[2];
*first_item ^= *third_item;
*third_item ^= *first_item;
*first_item ^= *third_item;
}
println!("{:?}", v);
}
Rust doesn't like this:
Compiling mcve v0.0.0 (/home/wizzwizz4/rust/mcve) error[E0499]: cannot borrow `v` as mutable more than once at a time --> src/main.rs:6:31 | 5 | let first_item = &mut v[0]; | - first mutable borrow occurs here 6 | let third_item = &mut v[2]; | ^ second mutable borrow occurs here 7 | *first_item ^= *third_item; | -------------------------- first borrow later used here error: aborting due to previous error For more information about this error, try `rustc --explain E0499`. error: Could not compile `mcve`. To learn more, run the command again with --verbose.
That's fine, because I only really want to change v[0]
:
fn main() {
let mut v = vec![0, 1, 2, 3, 4, 5, 6, 7];
{
let first_item = &mut v[0];
*first_item = v[2];
}
println!("{:?}", v);
}
I'm stuck again:
Compiling mcve v0.0.1 (/home/wizzwizz4/rust/mcve) error[E0502]: cannot borrow `v` as immutable because it is also borrowed as mutable --> src/main.rs:6:23 | 5 | let first_item = &mut v[0]; | - mutable borrow occurs here 6 | *first_item = v[2]; | --------------^--- | | | | | immutable borrow occurs here | mutable borrow later used here error: aborting due to previous error For more information about this error, try `rustc --explain E0502`. error: Could not compile `mcve`. To learn more, run the command again with --verbose.
The thing is, I know that both of those borrows are from different parts of the vector. Specifically, I know that the first index is <= 1
, and the second index is > 1
.
How do I tell the Rust compiler this?