Borrow checker Advanced
25 Disjoint borrows
The borrow checker won't let you hold overlapping mutable borrows -- but two parts of the same slice are provably disjoint. The starters below are broken on purpose: run them to see the error, then restructure so the compiler can see the borrows don't overlap.
Fix fold_halves so it adds each first-half value into the matching second-half slot. Split the slice into two disjoint mutable halves instead of borrowing it twice.
Hints
slice.split_at_mut(mid)hands you two non-overlapping&mutslices.let (a, b) = v.split_at_mut(mid);-- nowaandbcan be used together.
Reveal solution
fn fold_halves(v: &mut [i32]) {
let mid = v.len() / 2;
let (a, b) = v.split_at_mut(mid);
for i in 0..mid {
b[i] += a[i];
}
}