Last Updated: August 17, 2021
·
4.879K
· pornel

Take two or more mutable slices from a vector in Rust

In Rust there's a rule: a piece of memory can either have many readers or one writer at a time.

When you have a single chunk of memory (a slice or a vector) and you want to modify different parts of it via multiple slices, the borrow checker complains:

let whole = vec![1, 2, 3, 4, 5, 6];

let part1 = &mut whole[0..3];
let part2 = &mut whole[3..]; // Error!

This is because part1 has borrowed the whole already, and Rust doesn't care that the ranges are non-overlapping.

The solution to this is split_at_mut:

let (part1, part2) = whole.split_at_mut(3);

This gives you 2 (or more if you use it recursively) slices and the Rust compiler gets the guarantee that the ranges won't overlap, so everything is safe.