Sub topic 8
Mutable slices and splitting a buffer
This chapter covers &mut [T], the exclusive borrow of a slice. It explains why the compiler won't give you two mutable slices into the same buffer by default, and how split_at_mut and related methods hand out several at once.
It assumes you know ownership and moves, shared and mutable references, and the basics of Vec<T>, arrays, and &[T]. You should also know how range syntax such as &v[1..4] creates a slice.
What a mutable slice is
A &mut [T] is a mutable view of a run of elements stored contiguously in memory. The elements can belong to an array, a Vec<T>, or another slice. Like &[T], it holds a pointer and a length. Unlike &[T], it is an exclusive borrow, so while it is alive nothing else may read or write those elements.
You create one with &mut and a range, or by borrowing a whole collection mutably:
fn main() {
let mut data = vec![5, 4, 3, 2, 1, 0];
let middle = &mut data[1..5];
middle.sort();
middle[0] = 100;
println!("{:?}", data);
}This prints [5, 100, 2, 3, 4, 0]. Sorting middle reorders only elements 1 to 4 of data. The first and last elements are untouched. The final println! can use data again because middle is not used after middle[0] = 100, so its borrow has ended.
What you can and cannot do
A mutable slice lets you change elements in place. It does not let you change the length. There is no push, insert, or remove on a slice, because those operations may need to reallocate, and a slice does not own the allocation. If you need to grow the data, you need the owning Vec<T>.
These methods are the ones you will use most on &mut [T]:
| Method | Effect |
|---|---|
| `s[i] = x` | Overwrite one element (panics if out of range) |
| `s.iter_mut()` | Iterate with `&mut T` items |
| `s.fill(x)` | Set every element to a clone of `x` |
| `s.swap(i, j)` | Exchange two elements |
| `s.reverse()` | Reverse in place |
| `s.sort()` | Sort in place (needs `T: Ord`) |
| `s.copy_from_slice(src)` | Copy `src` into `s` (`T: Copy`, lengths must match) |
| `s.copy_within(range, dest)` | Copy part of the slice onto another part of itself (`T: Copy`) |
copy_from_slice panics if the two lengths differ. copy_within handles overlapping ranges correctly:
fn main() {
let mut v = [1, 2, 3, 4, 5];
v.copy_within(0..3, 2);
println!("{:?}", v);
let mut dst = [0; 3];
dst.copy_from_slice(&v[1..4]);
println!("{:?}", dst);
}The output is [1, 2, 1, 2, 3] and then [2, 1, 2].
Taking `&mut [T]` as a parameter
As with shared slices, a function that only needs to modify elements should accept &mut [T] rather than &mut Vec<T> or &mut [T; N]. One signature then serves arrays, vectors, and sub-ranges of either.
fn zero_fill(buf: &mut [u8]) {
for b in buf.iter_mut() {
*b = 0;
}
}
fn main() {
let mut v = vec![1u8; 6];
zero_fill(&mut v[2..4]);
println!("{:?}", v);
let mut arr = [9u8; 4];
zero_fill(&mut arr);
println!("{:?}", arr);
}This prints [1, 1, 0, 0, 1, 1] and then [0, 0, 0, 0]. The call zero_fill(&mut arr) works because &mut [u8; 4] coerces to &mut [u8] (unsized coercion). For a Vec, &mut v would coerce through DerefMut. The standard library already provides buf.fill(0), so this loop is only for illustration.
A &mut argument is not moved into the callee when the parameter type is a known &mut reference. The compiler reborrows it implicitly. You can therefore call zero_fill(buf) twice in a row with the same buf: &mut [u8].
Why the borrow checker limits you to one
The exclusivity rule applies to slices as it does to any &mut. A slice borrows the whole collection mutably for as long as the slice is used. Asking for a second mutable slice of the same collection while the first is alive is an error, even when the ranges don't overlap:
let mut v = vec![1, 2, 3, 4];
let a = &mut v[0..2];
let b = &mut v[2..4]; // error[E0499]: cannot borrow `v` as mutable more than once at a time
a[0] = b[0];The compiler reasons about borrows of v, not about the numeric ranges. &mut v[0..2] calls IndexMut::index_mut(&mut v, 0..2), and the range values are computed at runtime. The borrow checker only sees "v is mutably borrowed here". It cannot prove that 0..2 and 2..4 are disjoint, so it rejects the code.
Reading through v while a mutable slice is live is rejected for the same reason. For example, let first = v[0]; between creating a and using it fails, because v is mutably borrowed.
The rule has a real purpose. If two &mut slices could overlap, you could write through one while the other assumes the data is stable. Compilers rely on this guarantee for optimization, and your own code relies on it for correctness.
Splitting a buffer with `split_at_mut`
When you do want two non-overlapping mutable views, ask the standard library to split the slice. split_at_mut(mid) consumes one exclusive borrow and returns two exclusive borrows covering [0, mid) and [mid, len):
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]. Here left[0] = right[0] copies 4 into position 0. Then right[2] = left[1] * 10 writes 2 * 10 = 20 into the last position. You can read from one half while writing to the other because the two halves are provably disjoint.
How it stays safe
Inside the standard library, split_at_mut uses unsafe code. It builds two slices from raw pointers: one starting at the original pointer with length mid, and one starting mid elements later with length len - mid. The safe API is sound because of the checks it makes first:
- It asserts
mid <= lenand panics otherwise. - The two ranges cannot overlap by construction.
- The returned slices borrow from the input, so
vstays locked until both halves are done.
You get the benefit without writing unsafe yourself. This is a common Rust pattern: a small, audited unsafe core behind a safe interface.
Panic versus checked
split_at_mut(mid) panics when mid > len. Splitting at len is allowed and gives an empty right half. If mid comes from outside your program, use split_at_mut_checked (stable since Rust 1.80), which returns an Option:
fn main() {
let mut v = [1, 2, 3];
match v.split_at_mut_checked(5) {
Some(_) => println!("split"),
None => println!("mid out of range"),
}
if let Some((a, b)) = v.split_at_mut_checked(3) {
println!("{} {}", a.len(), b.len());
}
}The output is mid out of range and then 3 0.
A practical use: swapping two regions
Moving data between two parts of the same buffer is the usual reason to reach for split_at_mut. The method swap_with_slice exchanges the contents of two equally long mutable slices, and split_at_mut supplies them:
fn swap_halves(buf: &mut [i32]) {
let mid = buf.len() / 2;
let (left, right) = buf.split_at_mut(mid);
left.swap_with_slice(&mut right[..mid]);
}
fn main() {
let mut v = [1, 2, 3, 4, 5];
swap_halves(&mut v);
println!("{:?}", v);
}This prints [3, 4, 1, 2, 5]. For an odd length the right half is one element longer, so right[..mid] trims it to match. swap_with_slice panics if the two lengths differ, so that trim is required.
Other ways to get disjoint mutable pieces
split_at_mut is the base operation. These methods build on the same idea and are often more convenient:
split_first_mut()andsplit_last_mut()returnOption<(&mut T, &mut [T])>. They give you one element and the rest, and returnNonefor an empty slice.chunks_mut(n)yields non-overlapping&mut [T]pieces of up tonelements. The last piece may be shorter.chunks_exact_mut(n)yields only full chunks ofnelements and exposes the leftover throughinto_remainder().iter_mut()yields one&mut Tper element, all disjoint.
fn main() {
let mut v = [3, 1, 2];
if let Some((first, rest)) = v.split_first_mut() {
for x in rest.iter_mut() {
*x += *first;
}
*first = 0;
}
println!("{:?}", v);
let mut pixels = [0u8; 8];
for (i, chunk) in pixels.chunks_mut(4).enumerate() {
chunk[0] = i as u8 + 1;
chunk[3] = 255;
}
println!("{:?}", pixels);
}The first part prints [0, 4, 5]. Each later element gets the original first value (3) added, then the first element is cleared. The second part prints [1, 0, 0, 255, 2, 0, 0, 255], with each 4-byte chunk edited independently.
Note that there is no mutable counterpart of windows. Overlapping windows would give several &mut references to the same element, which the aliasing rules forbid. If you need overlapping access, index by position (v[i] and v[i + 1] in sequence) or use Cell types.
Common mistakes
- Taking two
&mut v[a..b]slices and expecting the compiler to see the ranges are disjoint. It will not. Usesplit_at_mutor a chunking method. - Passing
&mut Vec<T>when you only modify elements. This forces callers to own aVec. Accept&mut [T]unless the function must change the length. - Mismatched lengths in
copy_from_sliceorswap_with_slice. Both panic. Slice both sides to the same length first, for exampledst[..n].copy_from_slice(&src[..n]). - Holding a slice across a
push. AVec::pushmay reallocate and move the elements, so the borrow checker refuses to let a slice of the vector live across it. This is by design. Finish with the slice, then grow the vector. - Using
split_at_mutwith an unchecked index from user input. Usesplit_at_mut_checked, or validatemidfirst.
Summary
&mut [T]is an exclusive, fixed-length view into contiguous data. It can change elements but not the length.- The borrow checker treats a mutable slice as a mutable borrow of the whole collection, so it rejects two overlapping or even adjacent
&mut v[a..b]slices. split_at_mutreturns two disjoint&mutslices, and the standard library makes this safe with a bounds check around a small unsafe core.split_first_mut,chunks_mut, anditer_mutgive disjoint mutable access without manual splitting.- Prefer
split_at_mut_checkedwhen the split point is not already known to be valid.
Exercise
What does this program print, and why does it compile even though left and right both point into v?
fn main() {
let mut v = [10, 20, 30, 40];
let (left, right) = v.splitatmut(1);
right[0] += left[0];
left[0] = 0;
println!("{:?}", v);
}
Show answer
It prints [0, 30, 30, 40]. right[0] is v[1], which becomes 20 + 10 = 30. Then left[0] (v[0]) is set to 0. It compiles because split_at_mut returns two slices that cover disjoint ranges, [0, 1) and [1, 4), and it borrows v mutably once. The compiler only has to check that borrow, and the library guarantees the halves do not overlap. The println! is allowed because left and right are no longer used.
Exercise
Write a function rotate_pair(buf: &mut [i32], i: usize, j: usize) that swaps buf[i] and buf[j] using only split_at_mut, assuming i < j < buf.len(). Why is the plain buf.swap(i, j) still the better choice in real code?
Show answer
One solution:
fn rotatepair(buf: &mut [i32], i: usize, j: usize) {
let (left, right) = buf.splitatmut(j);
std::mem::swap(&mut left[i], &mut right[0]);
}
Splitting at j puts index i in left and index j at position 0 of right, so the two &mut references are disjoint. buf.swap(i, j) is better because it does the same thing in one call. It also handles i == j and either argument order, and it panics clearly on an out-of-range index. `splitat_mut` is for cases where you need two live mutable slices at once, not just a single swap.