Sub topic 6
Borrowing part of a Vec as a slice
This chapter assumes you know ownership and borrowing basics (&, &mut, moves), Option and match, and how to run programs with cargo. You should also have read the chapters on creating a Vec and on reading elements with indexing and get.
What a slice is
A slice is a borrowed view of a run of elements stored one after another in memory. Its type is written &[T], or &mut [T] when you may change the elements. A slice holds a pointer to the first element and a length. It owns nothing, so it cannot grow or shrink the data it points to.
You create a slice by borrowing a range of a Vec:
&v[..]is the whole Vec.&v[1..3]is the elements at index 1 and 2. The end is exclusive.&v[2..]runs from index 2 to the end.&v[..2]runs from the start up to, but not including, index 2.
Accept slices in function parameters
Write a function parameter as &[T] instead of &Vec<T>. Rust coerces a &Vec<T> to a &[T] automatically, so the same function accepts a whole Vec, a part of one, or an array.
fn largest(items: &[i32]) -> Option<&i32> {
items.iter().max()
}
fn main() {
let v = vec![4, 9, 2, 7];
println!("{:?}", largest(&v)); // Some(9)
println!("{:?}", largest(&v[1..3])); // Some(9)
println!("{:?}", largest(&[])); // None
}The return type Option<&i32> makes the empty case explicit. The returned reference points into the borrowed slice, so it is valid only while the original data is.
Slices follow the borrow rules
A slice is a reference, so the borrow checker treats it like any other. While a shared slice exists, you cannot call a method that needs &mut v, such as push. A push may reallocate the Vec and leave the slice pointing at freed memory, so the compiler rejects it.
fn main() {
let mut v = vec![1, 2, 3, 4];
let part = &v[1..3];
v.push(5); // error[E0502]: cannot borrow `v` as mutable
println!("{:?}", part);
}The error disappears once the last use of part comes before the push. This is the same rule you saw for &v[0].
Mutable slices
&mut v[range] gives you write access to part of a Vec. You can change elements in place, but you still cannot change the length.
fn main() {
let mut v = vec![5, 4, 3, 2, 1];
let tail = &mut v[2..];
tail.sort();
tail[0] = 10;
println!("{:?}", v); // [5, 4, 10, 2, 3]
}Here tail starts as [3, 2, 1]. After sort it is [1, 2, 3], and the assignment replaces the first element, so v becomes [5, 4, 10, 2, 3].
Out-of-range slices panic
Like indexing, slicing with a bad range panics at run time. &v[2..9] on a four-element Vec panics, and so does a range whose start is greater than its end. When the range comes from user input, use get, which accepts a range and returns an Option:
fn main() {
let v = vec![1, 2, 3, 4];
println!("{:?}", v.get(1..3)); // Some([2, 3])
println!("{:?}", v.get(2..9)); // None
}Summary of forms
| Type | Owns data | Can change length | Typical use |
|---|---|---|---|
| `Vec<T>` | Yes | Yes | Building and growing a list |
| `&[T]` | No | No | Reading any run of elements |
| `&mut [T]` | No | No | Changing elements in place |
Exercise
A function needs to read every element of a Vec<String> but must not change it. Which parameter type should it use, and what happens if you call v.push(...) while a slice from that function's result is still in use?
Show answer
Use &[String]. Passing &v coerces automatically. The push is rejected at compile time with a borrow error (E0502), because the slice holds a shared borrow of v and push needs a mutable one.
Exercise
Given let v = vec![10, 20, 30, 40, 50];, what does &v[1..4] contain, and what does v.get(3..8) return?
Show answer
&v[1..4] is [20, 30, 40]. v.get(3..8) returns None, because the end of the range is past the length of 5.