Sub topic 7
How the borrow checker treats slices
This chapter assumes you know basic Rust syntax, ownership and moves, shared (&) and mutable (&mut) references, and how to build arrays and Vec<T> values. You should also know how to create a slice with &v[a..b]. The chapter covers what a slice borrows, how long the borrow lasts, and which compiler errors you will see when you break the rules.
A slice borrows the whole owner
A slice is a reference. When you write &v[1..3], the compiler records a borrow of v, not of elements 1 and 2. The borrow checker reasons about variables and lifetimes, not about index ranges. Everything below follows from this.
The classic example is first_word. The returned &str points into the original String, so the String stays borrowed for as long as the returned slice is used.
fn first_word(s: &str) -> &str {
match s.find(' ') {
Some(i) => &s[..i],
None => s,
}
}
fn main() {
let mut text = String::from("hello world");
let word = first_word(&text);
// text.clear(); // error[E0502]: cannot borrow `text` as mutable
// // because it is also borrowed as immutable
println!("{}", word);
text.clear();
println!("cleared: {:?}", text);
}Uncommenting the first text.clear() fails because word is used afterwards. clear needs &mut text, and that cannot coexist with a live shared borrow. This is the bug the rule prevents. If clear ran first, word would point at memory that no longer holds the string.
The two rules, applied to slices
At any point in a program, a value can have either of these:
- any number of shared borrows, such as
&[T]or&str - exactly one mutable borrow, such as
&mut [T]
Shared slices can overlap freely. They can only read, so nothing can change under them.
fn sum(s: &[i32]) -> i32 {
s.iter().sum()
}
fn main() {
let v = vec![1, 2, 3, 4];
let a = &v[..2];
let b = &v[1..];
let c = &v[..];
println!("{} {} {}", sum(a), sum(b), sum(c));
}This prints 3 9 10. The three slices overlap on elements 1 and 2, and the compiler accepts it.
A mutable slice is exclusive. While it is alive, you cannot read or write the owner through any other path.
fn main() {
let mut v = vec![1, 2, 3, 4];
let m = &mut v[..2];
m[0] = 10;
// println!("{:?}", v); // error[E0502]: `v` is borrowed as mutable
m[1] = 20;
println!("{:?}", v);
}This prints [10, 20, 3, 4]. The commented println! would read v while m is still needed by the next line.
Borrows end at the last use
Since Rust 2018, borrows are not tied to the end of a {} block. A borrow lasts from its creation to its last use. This is called non-lexical lifetimes (NLL). Many programs that look wrong at first glance are fine under NLL.
fn main() {
let mut v = vec![1, 2, 3];
let head = &v[..2];
println!("{:?}", head); // last use of `head`
v.push(4); // allowed: the shared borrow is over
println!("{:?}", v);
}If you add a println!("{:?}", head); after the push, the program stops compiling. The diagram shows how the state of the owner changes.
Why `push` conflicts with a slice
A Vec stores its elements in a heap buffer. When push exceeds the capacity, the Vec allocates a larger buffer, copies the elements, and frees the old one. A slice taken earlier still holds the address of the old buffer. It would become a dangling pointer. The borrow checker refuses the call whether or not the push would actually reallocate, because it checks types and lifetimes, not run-time capacity.
The same reasoning applies to anything that can move or free the storage: push, insert, remove, clear, truncate, drop(v), or moving v into another function. Moving or dropping while a slice is live gives E0505 (cannot move out of v because it is borrowed).
Disjoint ranges still conflict
You might expect these two mutable slices to be fine, since they cover different elements:
fn main() {
let mut v = [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];
let (a, b) = v.split_at_mut(2);
a[0] = b[0];
println!("{:?}", v);
}This prints [3, 2, 3, 4]. Range indexing calls IndexMut::index_mut(&mut v, range). Each call borrows all of v, and the borrow checker does not look at the numbers in the range. split_at_mut makes one call that returns two non-overlapping slices. Internally it uses unsafe code, with the non-overlap guaranteed by the length check. The next chapters on mutable slices cover it in more detail.
Reborrowing
A &mut [T] is not Copy, so you might expect passing it to a function to move it. In practice the compiler inserts a reborrow, &mut *s, when the parameter type is a known &mut type. The reborrow is a temporary exclusive borrow of what s points to. When the function returns, the original s is usable again.
fn zero_first(s: &mut [i32]) {
if let Some(x) = s.first_mut() {
*x = 0;
}
}
fn main() {
let mut v = vec![5, 6, 7];
let s = &mut v[..];
zero_first(s);
zero_first(s); // not a use-after-move: each call reborrows `s`
s[1] = 9;
println!("{:?}", v);
}This prints [0, 9, 7]. Reborrowing is why helper functions can take &mut [T] without wrecking the caller's variable.
Lifetimes of returned slices
A function that returns a slice must say which input the slice comes from. With one reference parameter, lifetime elision handles this, as in first_word. With two or more, you must name the lifetimes:
fn longer<'a>(a: &'a [i32], b: &'a [i32]) -> &'a [i32] {
if a.len() >= b.len() { a } else { b }
}
fn main() {
let x = vec![1, 2, 3];
let result;
{
let y = vec![4, 5];
result = longer(&x, &y);
println!("{:?}", result);
}
// println!("{:?}", result); // error[E0597]: `y` does not live long enough
}This prints [1, 2, 3]. Using the same 'a for both inputs makes result valid only while both x and y are alive, even though this run returned x. The signature is what the compiler checks, not the body.
You cannot return a slice of a local owner. A function that builds a Vec and returns &v[..] fails with E0515 (cannot return value referencing local variable). Return the Vec itself instead, so the caller owns the data.
Sub-slicing a shared slice
Slicing a shared slice does not tie the result to the variable holding the reference. It ties the result to the data the reference points to.
fn main() {
let data = vec![1, 2, 3, 4];
let outer: &[i32] = &data;
let inner;
{
let tmp: &[i32] = outer; // shared references are Copy
inner = &tmp[1..3];
}
println!("{:?}", inner);
}This prints [2, 3]. tmp goes out of scope, but inner borrows data through it, not tmp itself. This works only for shared references. A &mut [T] reborrow cannot outlive the mutable reference it came from.
Common errors
| Error | Typical cause | Fix |
|---|---|---|
| `E0502` | Mutating or mutably borrowing the owner while a shared slice is still used later | Finish using the slice first, or copy the needed data out |
| `E0499` | Two `&mut` slices of the same owner alive together | Use `split_at_mut`, `chunks_mut`, or restructure |
| `E0505` | Moving or dropping the owner while a slice is alive | Use the slice before the move, or clone the data |
| `E0506` | Assigning to an element, such as `v[0] = 1`, while a slice borrows `v` | Write through the mutable slice, or end the borrow first |
| `E0597` | Slice outlives the owner in an inner scope | Declare the owner in an outer scope |
| `E0515` | Returning a slice of a local `Vec` or `String` | Return the owned value |
Working with the checker
- Convert a slice to an owned value when you need to keep data across a mutation:
let copy = v[..2].to_vec();. This ends the borrow at the cost of a copy. - Compute indices first and take the slice later. Storing a
usizeposition does not borrow anything, so it survives mutation of the owner. Storing a slice does not. - Keep slices short-lived. Create them near where they are used instead of holding them in long-lived variables.
- Prefer
&[T]parameters. They let callers pass&Vec<T>,&[T; N], or a sub-slice, and the callee cannot mutate the data.
Exercise
A function takes v: &mut Vec<i32>. It creates let first_two = &v[..2];, then calls v.push(0);, then prints first_two. Does it compile? If not, name the error and give two ways to fix it.
Show answer
It does not compile. first_two is a shared borrow of *v and is used after push, which needs a mutable borrow, so the compiler reports E0502. Fix 1: reorder so the print comes before the push, which ends the shared borrow first. Fix 2: copy the data with let first_two = v[..2].to_vec(); so no borrow of v remains. The same applies if v holds fewer than two elements. The conflict is found at compile time, and the slicing would panic at run time.
Exercise
Why does let a = &mut v[0..2]; let b = &mut v[2..4]; fail for an array v even though the ranges do not overlap, and which method fixes it?
Show answer
Each range index expression calls index_mut on the whole of v, so the compiler sees two simultaneous mutable borrows of v (E0499). It does not reason about the numeric ranges. v.split_at_mut(2) returns two non-overlapping mutable slices from a single borrow, and it fixes the error.