Sub topic 10
Slices as Borrowed Views
This chapter assumes you know the following:
- Basic Rust syntax.
- Ownership and moves.
- Shared and mutable references.
- The borrowing rule that a value can have many readers or one writer, never both.
Slices apply those rules to part of a collection.
What a slice is
A slice is a reference to a contiguous run of elements in something else. It owns nothing. It is a borrowed view of data that lives elsewhere, such as in a String, a Vec, or an array.
Slice types are written without an owner:
&stris a view of UTF-8 text.&[T]is a view of a run ofTvalues.&mut [T]is a mutable view of a run ofTvalues.
Internally a slice reference is a "fat pointer" with two machine words: the address of the first element and the number of elements. The slice itself, str or [T], has no size known at compile time, so you only use it behind a reference.
No bytes are copied when you create a slice. Creating one costs a pointer and a length, and the borrow checker treats it as a borrow of the owner.
Range syntax
You create a slice by indexing with a range and then taking a reference to the result.
fn main() {
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..];
let all = &s[..];
println!("{hello}|{world}|{all}");
}This prints hello|world|hello world. The range a..b includes a and excludes b. You can leave out the start (..b), the end (a..), or both (..). a..=b includes b.
The leading & is required. s[0..5] on its own is the unsized str, and Rust will not let you hold that by value.
A slice keeps its owner borrowed
A function that returns a slice ties the result to its input. This is the standard example from the plan:
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let text = String::from("ownership is rust's key idea");
let word = first_word(&text);
println!("{word}");
}The compiler treats word as a shared borrow of text. If you try to modify text while word is still in use, the program is rejected:
fn main() {
let mut text = String::from("ownership is rust's key idea");
let word = &text[0..9];
// text.clear(); // error[E0502]: cannot borrow `text` as mutable
// // because it is also borrowed as immutable
println!("{word}");
}clear needs &mut text. That conflicts with the live shared borrow, which lasts until the println!. A version that returned a usize index instead would compile, and then word would silently point at nothing after the clear. Returning a slice moves that bug from run time to compile time.
Array and vector slices
Slices work the same way for any element type.
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let a = [1, 2, 3, 4, 5];
let v = vec![10, 20, 30];
println!("{}", sum(&a[1..4]));
println!("{}", sum(&v));
println!("{}", sum(&a));
}The output is 9, 60, and 15. One function accepts a sub-range of an array, a whole Vec, and a whole array. &Vec<i32> and &[i32; 5] convert to &[i32] automatically. This is called deref coercion, and it is the reason to prefer slices in function parameters.
| Prefer | Over | Reason |
|---|---|---|
| `&str` | `&String` | Accepts string literals, `String`, and sub-slices |
| `&[T]` | `&Vec<T>` | Accepts arrays, vectors, and sub-slices |
| `&mut [T]` | `&mut Vec<T>` | Use when you only change elements, not the length |
Use &mut Vec<T> only when the function must push, pop, or otherwise change the length. A slice cannot grow or shrink.
String literals are slices
A literal such as "hello" has type &'static str. It is a slice into the program's read-only data, which lives for the whole run. That is why a function taking &str accepts literals and borrowed Strings alike. The 'static lifetime is covered in later chapters.
Mutable slices
A &mut [T] lets you change elements in place but not the length. The same exclusivity rule applies: while a mutable slice is live, nothing else may touch the owner.
Sometimes you want two mutable views into the same array. Two overlapping &mut borrows are illegal, but disjoint halves are safe. The standard library provides split_at_mut for this:
fn main() {
let mut data = [1, 2, 3, 4, 5, 6];
let (left, right) = data.split_at_mut(3);
left[0] = 100;
right[0] = 400;
println!("{:?}", data);
}This prints [100, 2, 3, 400, 5, 6]. The borrow checker cannot prove on its own that data[..3] and data[3..] do not overlap. split_at_mut is implemented with a small unsafe block inside the standard library, and its safe signature guarantees the halves are disjoint. After left and right are last used, data can be used directly again, so the final println! compiles.
Edge cases and panics
Slicing with [] panics at run time in three situations:
- The range end is past the length.
- The start is greater than the end.
- For
str, a boundary falls in the middle of a multi-byte UTF-8 character.
String indices count bytes, not characters. In "héllo", the letter é takes two bytes. The string's length is 6, not 5.
When the range comes from user input or other unchecked data, use get, which returns an Option instead of panicking:
fn main() {
let s = String::from("héllo");
println!("{}", s.len());
println!("{:?}", s.get(0..2));
println!("{:?}", s.get(0..3));
let v = [1, 2, 3];
println!("{:?}", v.get(1..5));
}The output is:
6
None
Some("hé")
Nones.get(0..2) is None because byte 2 falls inside é, which occupies bytes 1 and 2. An empty range such as &v[2..2] is valid and gives an empty slice. A range that starts at the length, such as &v[3..] on a length-3 array, is also valid.
Reading the errors
You will most often meet two slice-related messages:
cannot borrow ... as mutable because it is also borrowed as immutable(E0502). A slice is still in use while you mutate the owner. Finish using the slice first, or copy what you need withto_string()orto_vec(), which end the borrow.the size for values of type str cannot be known at compilation time. You wrotelet x = s[0..2];without the&.
Summary of the model
- A slice is a pointer plus a length, with no ownership.
- Creating a slice borrows the owner for as long as the slice is used.
- Shared slices follow the many-readers rule. A
&mutslice follows the one-writer rule. - Function parameters should usually be
&stror&[T]. - Use
getfor fallible slicing, andsplit_at_mutfor disjoint mutable views.
Exercise
This code does not compile. Why, and what is the smallest change that fixes it without cloning? fn main() { let mut v = vec![1, 2, 3]; let head = &v[..2]; v.push(4); println!("{:?}", head); }
Show answer
head is a shared borrow of v that is still used by the println! after v.push(4) needs &mut v. The two borrows overlap, which breaks the borrowing rules. Move the println! before v.push(4), so the slice's last use comes first and the borrow ends before the push.
Exercise
Given let s = String::from("naïve"); (where ï takes two bytes), what does &s[0..3] do, and what does s.get(0..3) return? What is the safe way to take the first three characters?
Show answer
&s[0..3] panics because byte 3 is in the middle of ï (bytes 2 and 3). s.get(0..3) returns None. To take the first three characters, find the byte offset with s.charindices().nth(3).map(|(i, )| i), or collect the characters with s.chars().take(3).collect::<String>(). The first approach gives a slice &s[..i] and the second an owned String.