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 2 / 2

Fix tweak: add 1 to every element, then double the first. Split off the first element so its borrow doesn't span the loop over the rest.

Hints
  • v.split_first_mut() yields Some((&mut first, &mut rest)), two disjoint borrows.
  • It returns None for an empty slice, so an if let handles that case for free.
25_disjoint_borrows.rs
Reset to starterCompiled in a sandbox; hidden checks must pass.
Reveal solution
fn tweak(v: &mut [i32]) {
    if let Some((first, rest)) = v.split_first_mut() {
        *first += 1;
        for x in rest.iter_mut() {
            *x += 1;
        }
        *first *= 2;
    }
}