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 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()yieldsSome((&mut first, &mut rest)), two disjoint borrows.- It returns
Nonefor an empty slice, so anif lethandles that case for free.
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;
}
}