Sub topic 7
How the Borrow Checker Treats Slices
This chapter assumes you know ownership, moves, and the basic rules of & and &mut. It also assumes you know how to build a slice with range syntax such as &v[1..3].
A slice borrows the whole container
A slice like &v[1..3] looks like it touches only two elements. The borrow checker does not see it that way. It tracks borrows by variable, not by index range. A shared slice of v is a shared borrow of all of v. A mutable slice of v is a mutable borrow of all of v.
The usual rules apply to that borrow:
- Any number of shared borrows may exist at once, but nothing may mutate the data while they live.
- One mutable borrow may exist, and nothing else may read or write the data while it lives.
| While this slice is alive | Reading `v` | Mutating `v` (such as `push`) | Another `&mut` slice of `v` |
|---|---|---|---|
| `&v[..]` | allowed | rejected | rejected |
| `&mut v[..]` | rejected | rejected | rejected |
Why `push` conflicts with a live slice
Suppose you take let head = &v[..2]; and then call v.push(4). If v is full, push allocates a bigger buffer, copies the elements, and frees the old one. head would then point at freed memory. The compiler rejects this with error E0502 ("cannot borrow v as mutable because it is also borrowed as immutable"). The check happens at compile time, so no such bug can exist at run time.
The error appears only if the slice is used after the mutation. Borrows last until their final use, not until the end of the scope. This is called non-lexical lifetimes.
fn main() {
let mut v = vec![1, 2, 3];
let head = &v[..2];
println!("{:?}", head); // last use of `head`
v.push(4); // fine: the shared borrow has ended
println!("{:?}", v);
}This prints [1, 2] and then [1, 2, 3, 4]. If you moved the first println! to after the push, the program would no longer compile.
Mutable slices are exclusive
The same logic applies to &mut slices. While the mutable slice is live, you cannot read the original container.
fn main() {
let mut a = [1, 2, 3, 4];
let front = &mut a[..2];
front[0] = 9;
// println!("{:?}", a); // would fail here: `front` is used below
front[1] = 8;
println!("{:?}", a); // fine: `front` is no longer used
}This prints [9, 8, 3, 4]. The commented println! would be an E0502 error, because front is still used afterward.
Disjoint ranges are still one borrow
Two mutable slices of different parts of one array look safe, since they never overlap. The compiler still rejects let x = &mut a[..2]; let y = &mut a[2..]; with E0499 ("cannot borrow a as mutable more than once"). Indexing with a range calls IndexMut on the whole container, and the compiler cannot reason about the numeric ranges.
When you need two non-overlapping mutable views, ask the standard library to split the borrow for you. split_at_mut uses a small amount of unsafe code inside and exposes a safe interface.
fn main() {
let mut a = [1, 2, 3, 4];
let (x, y) = a.split_at_mut(2);
x[0] = y[1];
y[0] = 0;
println!("{:?}", a);
}This prints [4, 2, 0, 4]. The next chapter covers mutable slices in more detail.
Slices returned from functions
A function that returns a slice ties the result to its input. With one reference parameter, lifetime elision does this for you.
fn largest_half(s: &[i32]) -> &[i32] {
&s[s.len() / 2..]
}
fn main() {
let mut data = vec![5, 6, 7, 8];
let half = largest_half(&data);
println!("{:?}", half);
data.clear(); // fine: `half` is not used again
println!("{}", data.len());
}The returned slice borrows from data. If you used half after data.clear(), the compiler would reject it. With two slice parameters, elision cannot choose, so you must name a lifetime such as fn pick<'a>(a: &'a [i32], b: &[i32]) -> &'a [i32].
Common errors and fixes
- E0502 after
push,clear, orinsert: a slice is still live. Finish using the slice first, or copy what you need withto_vec()before mutating. - E0499 on two
&mutranges: usesplit_at_mut,chunks_mut, orsplit_first_mut. - E0506 on assigning
v[0] = xwhile a slice is live: the slice borrows all ofv, so an element write conflicts with it. - Holding a slice across a loop that mutates the source: collect the indices or values you need first, then mutate.
Exercise
This code fails with E0502. Why, and what is the smallest change that makes it compile? fn main() { let mut v = vec![1, 2, 3]; let tail = &v[1..]; v.push(4); println!("{:?}", tail); }
Show answer
tail is a shared borrow of all of v, and it is still used after v.push(4), which needs a mutable borrow. Because push may reallocate, tail could dangle. Moving the println! above the push ends the borrow first and fixes it. Alternatively, copy the data with let tail = v[1..].to_vec();, which owns its data and does not borrow v.
Exercise
Why does let x = &mut a[..2]; let y = &mut a[2..]; fail even though the ranges do not overlap, and which method solves it?
Show answer
Each range expression is a mutable borrow of the whole array a, and the borrow checker does not compare index ranges. Two live mutable borrows of a give E0499. a.split_at_mut(2) returns two non-overlapping mutable slices from a single borrow.