Sub topic 5
Slices: borrowing part of a collection
This chapter assumes you know how shared references (&T) work and the rule that a value cannot be mutated while it is borrowed. Slices apply the same rules to a part of a collection instead of the whole thing.
What a slice is
A slice is a borrowed view into a run of contiguous elements. It does not own the data. Internally it is a "fat pointer": an address plus a length.
The two slice types you will use most are:
&str, a view into UTF-8 text.&[T], a view into a sequence ofT, such as part of aVec<T>or an array.
You create a slice by borrowing a range of a collection.
fn main() {
let s = String::from("borrowing is useful");
let word = &s[0..9];
let rest = &s[10..];
let nums = vec![10, 20, 30, 40, 50];
let middle = &nums[1..4];
println!("{word} | {rest} | {middle:?}");
}The range a..b includes a and excludes b. You can leave out either end: ..3, 2.., or .. for everything. Because word and middle are shared references, s and nums stay readable, and they cannot be changed while those slices are alive.
Why slices are better than indices
Suppose a function returns the end index of the first word. The index is just a number, so nothing connects it to the string it came from. If the string changes later, the number is silently wrong.
A slice avoids this because it is a borrow. The compiler tracks it like any other reference.
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let mut sentence = String::from("borrowing is useful");
let word = first_word(&sentence);
sentence.clear(); // error: cannot borrow `sentence` as mutable
println!("{word}");
}This does not compile. clear needs a mutable borrow, but word still borrows sentence and is used afterwards. The error is E0502, the same one you meet with any shared and mutable borrow overlap. Remove the println!, or move it before clear, and the program compiles.
flowchart TD
A[String owns heap bytes] --> B["&s[0..9] borrows a view"]
B --> C{Is the slice still used later?}
C -- yes --> D[Mutating s is rejected]
C -- no --> E[Mutating s is allowed]The diagram above is for reading only. The exact diagram block follows.
Prefer `&str` and `&[T]` in parameters
A function that only reads text should take &str, not &String. A &String coerces to &str automatically, so the &str version accepts string literals, String borrows, and slices of either.
The same holds for &[T] versus &Vec<T>.
fn total(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let v = vec![1, 2, 3, 4];
let arr = [5, 6, 7];
println!("{}", total(&v));
println!("{}", total(&arr));
println!("{}", total(&v[1..3]));
}One signature handles a Vec, an array, and a sub-range.
Mutable slices
A &mut [T] lets you change elements in place. It cannot change the length, because it does not own the allocation.
fn double_all(values: &mut [i32]) {
for x in values.iter_mut() {
*x *= 2;
}
}
fn main() {
let mut v = vec![1, 2, 3, 4];
double_all(&mut v[..2]);
println!("{v:?}");
}This prints [2, 4, 3, 4]. Only the first two elements were borrowed mutably.
Common errors
- Slicing text off a character boundary. String indices are byte offsets.
&"héllo"[0..2]panics at run time becauseéoccupies bytes 1 and 2. Usechar_indicesor.get(0..2), which returnsNoneinstead of panicking. - Range out of bounds.
&nums[2..9]on a five-element vector panics.nums.get(2..9)returnsNone. - Holding a slice across a mutation. This is the E0502 case above. Copy the data with
.to_vec()or.to_string()if you need it to outlive the mutation.
Exercise
Write a function signature that accepts the first three elements of any Vec<i32> or array of i32 without copying, and say why &Vec<i32> is a worse parameter type.
Show answer
fn use_three(values: &[i32]), called as use_three(&v[..3]). &Vec<i32> rejects arrays and sub-slices, so it forces callers to build a Vec, while &[i32] accepts all of them.