The split_at_mut function (for splitting mutable slices at an index) requires unsafe code (according to the Rust book) to be implemented. But the book also says: "Borrowing different parts of a slice is fundamentally okay because the two slices aren’t overlapping".
My question: Why does the borrow checker not understand that borrowing different parts of a slice is fundamentally okay? (Is there a reason preventing the borrow checker from understanding this rule or is it just that it has not been implemented for some reason?)
Trying the suggested code with Rust 1.48 still results in the error shown in the book:
fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
let len = slice.len();
assert!(mid <= len);
(&mut slice[..mid], &mut slice[mid..])
}
fn main() {
let mut vector = vec![1, 2, 3, 4, 5, 6];
let (left, right) = split_at_mut(&mut vector, 3);
println!("{:?}, {:?}", left, right);
}
Gives error message:
error[E0499]: cannot borrow `*slice` as mutable more than once at a time
--> src/main.rs:6:30
|
1 | fn split_at_mut(slice: &mut [i32], mid: usize) -> (&mut [i32], &mut [i32]) {
| - let's call the lifetime of this reference `'1`
...
6 | (&mut slice[..mid], &mut slice[mid..])
| -------------------------^^^^^--------
| | | |
| | | second mutable borrow occurs here
| | first mutable borrow occurs here
| returning this value requires that `*slice` is borrowed for `'1`