Sub topic 6
Borrowing Part of a Vec as a Slice
This chapter assumes you know how to create a Vec, read elements with indexing and get, and iterate over it. It also assumes you know the basic borrowing rules: any number of & borrows, or one &mut, never both at once.
What a slice is
A slice is a view into a run of consecutive elements. Its type is [T], but you almost always use it behind a reference: &[T] for read-only access and &mut [T] for read-write access.
A slice reference is a "fat pointer" made of two values: the address of the first element and the number of elements. It owns nothing. It cannot grow or shrink, and it never frees memory. The Vec still owns the buffer.
Creating slices with ranges
Index a Vec with a range and borrow the result with &:
fn main() {
let v = vec![10, 20, 30, 40, 50];
let a = &v[..2]; // [10, 20]
let b = &v[2..]; // [30, 40, 50]
let c = &v[1..=3]; // [20, 30, 40]
let d = &v[..]; // the whole Vec as a slice
println!("{:?} {:?} {:?} {}", a, b, c, d.len());
// [10, 20] [30, 40, 50] [20, 30, 40] 5
}The start of a range is inclusive and the end is exclusive. ..= makes the end inclusive. Leaving out either side means "from the beginning" or "to the end".
The & matters. v[1..3] on its own has type [i32], which has no size known at compile time, so you cannot bind it to a variable. &v[1..3] is a &[i32], which you can.
Out-of-range ranges
Like single-element indexing, range indexing panics when the range is bad. It panics if the end is past len() or if the start is greater than the end. The checked version is get with a range, which returns an Option:
fn main() {
let v = vec![10, 20, 30, 40, 50];
println!("{:?}", v.get(1..3)); // Some([20, 30])
println!("{:?}", v.get(2..10)); // None
println!("{:?}", v.get(4..2)); // None
}Use get(range) whenever the bounds come from user input, a file, or a network message.
Accept slices in function parameters
A function that only reads a sequence should take &[T], not &Vec<T>. A &Vec<i32> is automatically converted to a &[i32] where a slice is expected. This is called deref coercion. A slice parameter accepts more callers:
fn largest(items: &[i32]) -> Option<&i32> {
items.iter().max()
}
fn main() {
let v = vec![4, 9, 2, 7];
let arr = [1, 8, 3];
println!("{:?}", largest(&v)); // Some(9)
println!("{:?}", largest(&v[1..3])); // Some(9)
println!("{:?}", largest(&arr)); // Some(8)
println!("{:?}", largest(&[])); // None
}A &Vec<i32> parameter would reject the array, the sub-range, and the empty literal. It would also promise methods like push that a read-only function cannot use anyway.
| Parameter type | Accepts | Can change elements | Can change length |
|---|---|---|---|
| `&[T]` | `&Vec<T>`, `&[T; N]`, sub-slices | No | No |
| `&mut [T]` | `&mut Vec<T>`, `&mut [T; N]`, mutable sub-slices | Yes | No |
| `&Vec<T>` | Only `&Vec<T>` | No | No |
| `&mut Vec<T>` | Only `&mut Vec<T>` | Yes | Yes |
| `Vec<T>` | An owned `Vec<T>` (moves it) | Yes, if declared `mut` | Yes, if declared `mut` |
Mutable slices
&mut v[range] gives write access to part of a Vec. Slices cannot change length, so they have no push. They do have methods such as sort, reverse, swap and fill:
fn zero_first_half(items: &mut [i32]) {
let mid = items.len() / 2;
items[..mid].fill(0);
}
fn main() {
let mut v = vec![1, 2, 3, 4, 5, 6];
zero_first_half(&mut v);
println!("{:?}", v); // [0, 0, 0, 4, 5, 6]
v[3..].reverse();
println!("{:?}", v); // [0, 0, 0, 6, 5, 4]
}Two mutable pieces at once
The compiler cannot see that &mut v[..2] and &mut v[2..] do not overlap, so it rejects holding both. Use split_at_mut, which returns two non-overlapping mutable slices:
fn main() {
let mut v = vec![1, 2, 3, 4];
let (left, right) = v.split_at_mut(2);
left[0] = right[1];
right[0] += left[1];
println!("{:?}", v); // [4, 2, 5, 4]
}split_at_mut is implemented with a small amount of unsafe code inside the standard library. Its public interface is safe, because it checks the split point and guarantees the halves are disjoint.
Slices borrow the Vec
A slice keeps the Vec borrowed for as long as the slice is used. This is the same rule as for &v[0]. A push may reallocate the buffer, which would leave the slice pointing at freed memory, so the compiler forbids it:
fn main() {
let mut v = vec![1, 2, 3];
let head = &v[..2];
// v.push(4); // error[E0502]: cannot borrow `v` as mutable
// // because it is also borrowed as immutable
println!("{:?}", head); // last use of head
v.push(4); // fine: the borrow ended after the println
println!("{:?}", v); // [1, 2, 3, 4]
}The borrow lasts until the last use of head, not until the end of the block. If the error appears, either finish using the slice before mutating, or copy the data out with to_vec():
fn main() {
let mut v = vec![1, 2, 3, 4, 5];
let middle: Vec<i32> = v[1..4].to_vec(); // owned copy, no borrow remains
v.push(6);
println!("{:?} {:?}", middle, v); // [2, 3, 4] [1, 2, 3, 4, 5, 6]
}to_vec requires T: Clone. For types like String it clones every element, which costs time and memory. Prefer finishing the read before the mutation when you can.
Useful slice methods
Many methods you call on a Vec are really slice methods reached through deref. A few more that are specific to working with parts of a sequence:
fn main() {
let v = vec![1, 4, 9, 16, 25, 36, 49];
// Differences between neighbours: overlapping windows of 2.
let diffs: Vec<i32> = v.windows(2).map(|w| w[1] - w[0]).collect();
println!("{:?}", diffs); // [3, 5, 7, 9, 11, 13]
// Non-overlapping chunks; the last one may be shorter.
for chunk in v.chunks(3) {
println!("{:?} sum={}", chunk, chunk.iter().sum::<i32>());
}
// [1, 4, 9] sum=14
// [16, 25, 36] sum=77
// [49] sum=49
println!("{:?} {:?}", v.first(), v.last()); // Some(1) Some(49)
println!("{}", v.contains(&16)); // true
}windows(n) and chunks(n) panic if n is 0. windows(n) yields nothing if the slice is shorter than n.
Matching on slice patterns
A slice can be matched with patterns that describe its length and shape. Call as_slice() to get a &[T] from a Vec:
fn describe(v: &Vec<i32>) -> String {
match v.as_slice() {
[] => String::from("empty"),
[only] => format!("one element: {only}"),
[first, .., last] => format!("starts with {first}, ends with {last}"),
}
}
fn main() {
println!("{}", describe(&vec![])); // empty
println!("{}", describe(&vec![7])); // one element: 7
println!("{}", describe(&vec![3, 5, 8])); // starts with 3, ends with 8
}The three arms cover every possible length, so the match is exhaustive. This avoids the v[0] and v[v.len() - 1] panics on empty input.
Common errors
- Forgetting
&.let s = v[1..3];fails with "the size for values of type[i32]cannot be known". Write&v[1..3]. - Off-by-one in
..=.&v[0..=v.len()]panics, because the last valid index islen() - 1. - Mutating while a slice is alive. Any
push,insert,removeorclearon theVecconflicts with a live slice borrow. - Overlapping mutable slices. Use
split_at_mut,chunks_mut, or restructure the code. - Slicing text by byte offsets.
&s[0..1]on aStringis a&strslice and panics if the range cuts through a multi-byte character. Vector slices index elements, but string slices index bytes.
Exercise
Write a function fn sum_of_last(items: &[i32], n: usize) -> Option<i32> that returns the sum of the last n elements, or None if the slice has fewer than n elements. Which slice operations make it panic-free?
Show answer
Compute the start with checked_sub, then take a checked slice with get:
fn sumoflast(items: &[i32], n: usize) -> Option<i32> {
let start = items.len().checkedsub(n)?;
Some(items.get(start..)?.iter().sum())
}
If n > items.len(), `checkedsub returns None and ? returns early, so the code never subtracts below zero. get(start..) is also checked, so no indexing can panic. With n == 0 the start equals len()`, the slice is empty, and the sum is 0.
Exercise
This code does not compile. Why, and what is the smallest change that fixes it? let mut v = vec![1, 2, 3]; let firsttwo = &v[..2]; v.push(4); println!("{:?}", firsttwo);
Show answer
first_two borrows v immutably and is used after v.push(4), which needs a mutable borrow, so the borrows overlap. The smallest fix is to move the println! before the push, so the slice's last use comes first. Alternatively, copy the data with let first_two = v[..2].to_vec();, which owns its elements and holds no borrow of v.