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.

Step 1 / 2

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 &mut slices.
  • let (a, b) = v.split_at_mut(mid); -- now a and b can be used together.
25_disjoint_borrows.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
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];
    }
}