Sub topic 8
Mutable slices and splitting a buffer
This chapter assumes you know ownership, references, and the shared-versus-mutable borrowing rules. It also assumes you have seen &[T] and range slicing like &v[1..4]. Here you will see how the same ideas apply when a slice lets you change the data it borrows.
Mutable slices: &mut [T]
A mutable slice has the type &mut [T]. It is a view into part of an array or vector that lets you read and write the elements, but not add or remove them. The length is fixed because the slice does not own the storage.
You create one by putting &mut in front of a range expression:
fn double_all(xs: &mut [i32]) {
for x in xs.iter_mut() {
*x *= 2;
}
}
fn main() {
let mut v = vec![1, 2, 3, 4, 5];
double_all(&mut v[1..4]);
println!("{:?}", v);
}This prints [1, 4, 6, 8, 5]. Only the elements at indexes 1 to 3 changed. The function does not know whether it received a whole Vec, part of an array, or a sub-range. It only sees &mut [i32].
The original variable must be declared mut. Without it, &mut v[1..4] is a compile error.
The exclusivity rule still applies
A &mut [T] follows the usual rule: while it is alive, nothing else may read or write the same data. The rule is checked on the whole region the slice covers, and the borrow checker treats the borrowed collection as one unit.
That causes a common surprise. Suppose you want two mutable views of one vector, such as &mut v[..3] and &mut v[3..]. The ranges do not overlap, but the compiler rejects the code with error E0499 ("cannot borrow v as mutable more than once at a time"). Each range expression goes through IndexMut::index_mut, which borrows all of v. The compiler does not evaluate the range values to prove the pieces are disjoint.
Splitting a buffer with split_at_mut
The standard library solves this with split_at_mut. It takes a mutable slice and an index, and returns two non-overlapping mutable slices. The implementation uses a small amount of unsafe code internally. The public API is safe because the two halves cannot overlap.
fn main() {
let mut v = [1, 2, 3, 4, 5, 6];
let (left, right) = v.split_at_mut(3);
left[0] = right[0];
right[2] = left[1] * 10;
println!("{:?}", v);
}This prints [4, 2, 3, 4, 5, 20]. The first line copies right[0] (4) into left[0]. The second line writes left[1] * 10 (20) into the last element of right. Both halves are live at once, and the borrow checker accepts it.
Once left and right are no longer used, the borrow ends and you can use v directly again. This is the non-lexical lifetimes rule applied to slices.
split_at_mut panics if the index is greater than the length. An index equal to the length is allowed, and the right slice is then empty.
Other ways to get disjoint pieces
You do not always have to split by hand. Several methods return mutable pieces that are already guaranteed not to overlap:
| Method | What it gives you |
|---|---|
| `split_at_mut(i)` | Two slices: `[..i]` and `[i..]` |
| `split_first_mut()` | `Option` of the first element and the rest |
| `split_last_mut()` | `Option` of the last element and the rest |
| `chunks_mut(n)` | An iterator of non-overlapping `&mut [T]` pieces of length `n` (the last may be shorter) |
| `iter_mut()` | An iterator of `&mut T`, one per element |
chunks_mut is useful when a buffer is made of fixed-size records:
fn main() {
let mut buf = [0u8; 6];
for (i, chunk) in buf.chunks_mut(2).enumerate() {
chunk.fill(i as u8 + 1);
}
println!("{:?}", buf);
}This prints [1, 1, 2, 2, 3, 3]. Each loop iteration gets its own chunk, so the compiler knows the writes cannot collide.
Common mistakes
- Taking
&mut Vec<T>when you only edit elements. Prefer&mut [T]. It accepts arrays and sub-ranges too, and it makes clear that the function cannot change the length. - Trying to
pushthrough a slice. Slices have nopush. You need the owningVec. - Holding one half while reusing the original. Using
vwhileleftorrightis still needed causes a borrow error. Finish with the halves first. - Splitting at an out-of-range index.
split_at_mutpanics, so check the length first when the index comes from input.
Exercise
You write let a = &mut v[0..2]; let b = &mut v[2..4]; a[0] = b[0]; on a Vec<i32> named v, and the compiler reports E0499. Why does it fail even though the ranges do not overlap, and how do you fix it?
Show answer
Each &mut v[..] expression borrows all of v mutably, because the compiler does not use the range values to prove the pieces are disjoint. The two mutable borrows are alive at the same time, which is not allowed. Fix it with let (a, b) = v.split_at_mut(2); (after making sure v.len() >= 2), then a[0] = b[0];. The two returned slices are guaranteed not to overlap.