Open
Description
The following code is invalid due to lifetime rules:
fn main() {
let mut foo = [1,2,3,4];
let mut a = &mut foo[..2];
let mut b = &mut foo[2..];
a[0] = 5;
b[0] = 6;
println!("{:?} {:?}", a, b);
}
error[E0499]: cannot borrow `foo` as mutable more than once at a time
--> src/main.rs:4:22
|
3 | let mut a = &mut foo[..2];
| --- first mutable borrow occurs here
4 | let mut b = &mut foo[2..];
| ^^^ second mutable borrow occurs here
5 | a[0] = 5;
| ---- first borrow later used here
The solution is to either use unsafe
or (more appropriately) use split_at_mut
:
fn main() {
let mut foo = [1,2,3,4];
let (mut a, mut b) = foo.split_at_mut(2);
a[0] = 5;
b[0] = 6;
println!("{:?} {:?}", a, b);
}
The compiler should detect the case of multiple mutable borrows to the same array/slice and hint at the existence of split_at_mut
. Ideally, we would also verify wether there's a range overlap in order to explain to the user why what they want to do is problematic and disallowed in Rust.
The output should ideally be along the lines of the following (the structured suggestion is not needed to fix this issue, the text would be enough of an improvement):
error[E0499]: cannot borrow `foo` as mutable more than once at a time
--> src/main.rs:4:22
|
3 | let mut a = &mut foo[..2];
| --- first mutable borrow occurs here
4 | let mut b = &mut foo[2..];
| ^^^ second mutable borrow occurs here
5 | a[0] = 5;
| ---- first borrow later used here
= note: you cannot have multiple mutable borrows to the same piece of memory, as the compiler cannot assure that the different slices you're trying to use are non-overlapping
help: you can instead use `split_at_mut` to get two non-overlapping mutable slices from a single array/slice
|
3 | let (mut a, mut b) = foo.split_at_mut(2);
| ^^^^^^^^^^^^^^ ^^^^^^^^^^^^^^^^^^^