Sub topic 10
Slices as Borrowed Views
This chapter assumes you know how shared references (&T) and mutable references (&mut T) work, and the borrowing rules from the previous chapters. It also assumes you are comfortable with String, Vec, and &str.
What a slice is
A slice is a borrowed view of a contiguous part of a collection. It does not own the data. Internally it is a "fat pointer": an address plus a length. Because a slice is a reference, all the borrowing rules apply to it.
The two slice types you will use most are &str (a view into text) and &[T] (a view into an array or Vec).
String slices
A range in square brackets creates a slice. Ranges are byte offsets, and &str must be valid UTF-8.
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}");
}word borrows from text. The compiler ties the slice's validity to text, so text cannot be changed or dropped while word is still in use.
Array and Vec slices
The same idea works for any contiguous sequence.
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let v = vec![10, 20, 30, 40, 50];
println!("{}", sum(&v));
println!("{}", sum(&v[1..4]));
}&v is a &Vec<i32>. Rust coerces it to &[i32] automatically. Taking &[T] instead of &Vec<T> is the usual choice for function parameters, because it accepts arrays, vectors, and sub-ranges.
Slices and the borrow checker
A slice keeps its source borrowed. The following code does not compile.
fn main() {
let mut s = String::from("hello world");
let word = &s[0..5];
s.clear(); // error: cannot borrow `s` as mutable
println!("{word}");
}s.clear() needs a mutable borrow, but word holds a shared borrow that is still used afterwards. If this compiled, word would point at emptied memory. Moving the println! above s.clear() fixes it, because the shared borrow ends at its last use.
Common errors
| Error | Cause | Fix |
|---|---|---|
| Cannot borrow as mutable | A slice is still used after the mutation | Use the slice before mutating, or copy it with `to_string()` |
| Panic: byte index is not a char boundary | A `&str` range cuts through a multi-byte character | Use `char_indices()` or choose valid boundaries |
| Panic: range out of bounds | The range end exceeds the length | Check `len()` or use `get(range)`, which returns an `Option` |
fn main() {
let s = "héllo";
println!("{:?}", s.get(0..2)); // None: 'é' spans bytes 1..3
println!("{:?}", s.get(0..3)); // Some("hé")
}Exercise
Why does let w = &s[0..5]; s.push('!'); println!("{w}"); fail to compile, and how do you fix it?
Show answer
w is a shared borrow of s that is used after s.push('!'), which needs a mutable borrow. The two overlap, so the borrow checker rejects it. Fix it by printing w before calling push, so the shared borrow ends first. You can also copy the text with let w = s[0..5].to_string();, which gives an owned value that does not borrow s.