Sub topic 5
Slices: Borrowing Part of a Collection
This chapter assumes you know how shared references (&T) work, how String, Vec, and &str differ, and that a value has one owner. It also assumes you can build and run a program with cargo. Here you will learn what a slice is, how it relates to the borrowing rules, and where slices go wrong.
What a slice is
A slice is a borrowed view of a contiguous run of elements inside a collection. It does not own the data. The slice types are:
&str, a view into UTF-8 text.&[T], a view into a run ofTvalues, such as part of aVec<T>, an array, or another slice.&mut [T], a mutable view into the same kind of data.
A slice reference is a "fat pointer". It holds two machine words: the address of the first element and the number of elements. The type [T] itself has no size known at compile time, so you always use it behind a reference (or a Box, Rc, and so on). That is why you write &[i32] and never a bare [i32] in a function parameter.
Because the slice only borrows, the original collection stays the owner. All the borrowing rules from the earlier chapters apply to it.
String slices
The most common slice is &str. You create one by indexing a String or another &str with a range:
fn main() {
let s = String::from("hello world");
let hello = &s[0..5];
let world = &s[6..11];
println!("{hello} {world}");
}The range is in bytes, not characters. Rust strings are UTF-8, so a character can take one to four bytes. If a range boundary falls inside a character, the program panics at run time:
fn main() {
let s = String::from("héllo");
// 'é' occupies bytes 1 and 2, so index 2 is not a character boundary.
let bad = &s[0..2];
println!("{bad}");
}This compiles, then panics with a message such as "byte index 2 is not a char boundary". When the input is not guaranteed to be ASCII, use s.get(0..2), which returns an Option<&str> instead of panicking, or iterate with chars().
Range syntax has shortcuts. &s[..5] starts at the beginning, &s[6..] runs to the end, &s[..] covers everything, and &s[2..=4] includes the end index.
String literals are slices
A string literal such as "hello" has type &'static str. It is a slice pointing into the compiled program's read-only data, and it stays valid for the whole run. This is why a function that takes &str accepts both literals and borrowed String values.
Array and vector slices
Slicing a Vec or an array works the same way, with element indexes:
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let v = vec![1, 2, 3, 4, 5];
let arr = [10, 20, 30];
println!("{}", sum(&v)); // whole Vec, as a slice
println!("{}", sum(&v[1..4])); // part of the Vec
println!("{}", sum(&arr)); // an array
}Passing &v where &[i32] is expected works through deref coercion. The compiler automatically converts &Vec<i32> to &[i32] and &String to &str, because Vec<T> implements Deref<Target = [T]> and String implements Deref<Target = str>. Arrays coerce to slices by unsizing coercion.
Prefer slices in parameters
Compare these two signatures:
| Parameter type | Accepts |
|---|---|
| `&String` | Only a borrowed `String` |
| `&str` | A borrowed `String`, a literal, or any other `&str` |
| `&Vec<T>` | Only a borrowed `Vec<T>` |
| `&[T]` | A borrowed `Vec<T>`, an array, or any sub-slice |
The slice version is strictly more flexible for the caller and costs nothing extra. Clippy flags &String and &Vec<T> parameters for this reason (the ptr_arg lint). Use &String or &Vec<T> only when the function needs something specific to that type, such as capacity().
The first_word example from the plan shows the pattern:
fn first_word(s: &str) -> &str {
s.split_whitespace().next().unwrap_or("")
}
fn main() {
let sentence = String::from("borrowing is useful");
let word = first_word(&sentence);
println!("{word}");
}The returned &str borrows from the input. Lifetime elision ties the result to the single input reference, a rule covered in a later chapter.
Slices keep the owner locked
The main reason slices matter for borrowing is that a slice is a real borrow. While it is alive, the owner cannot be changed in a way that might invalidate it.
Consider an index-based design that returns a usize instead of a slice:
fn first_word_end(s: &str) -> usize {
s.find(' ').unwrap_or(s.len())
}
fn main() {
let mut s = String::from("hello world");
let end = first_word_end(&s);
s.clear();
// `end` is still 5, but `s` is now empty.
println!("{end}");
}This compiles, and end is now meaningless. Nothing ties the number to the string. Returning a slice moves this bug from run time to compile time:
fn main() {
let mut s = String::from("hello world");
let word = &s[..5];
s.clear();
println!("{word}");
}s.clear() needs a mutable borrow of s, but word holds a shared borrow that is used afterwards. The compiler rejects this with error E0502 (cannot borrow s as mutable because it is also borrowed as immutable). This is the same "many readers or one writer" rule you saw with v.push while first was alive. The vector version is the same problem: a push can reallocate the buffer, which would leave a slice pointing at freed memory.
If you move the println! above s.clear(), the code compiles, because non-lexical lifetimes end the borrow after its last use.
Mutable slices
A &mut [T] lets you change elements in place, but not the length. The function cannot push or remove, because it does not own the buffer.
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[1..3]);
println!("{:?}", v);
}This prints [1, 4, 6, 4]. Only the middle two elements changed.
Two mutable slices of one buffer
Rust forbids two &mut borrows of the same value at once, and the compiler treats v[0..2] and v[2..4] as borrows of all of v. This fails:
fn main() {
let mut v = vec![1, 2, 3, 4];
let a = &mut v[0..2];
let b = &mut v[2..4];
a[0] = 10;
b[0] = 30;
println!("{:?}", v);
}The compiler cannot prove the ranges do not overlap, so it reports E0499 (cannot borrow v as mutable more than once at a time). The standard library provides split_at_mut for this. It checks the split point at run time and returns two non-overlapping mutable slices:
fn main() {
let mut v = vec![1, 2, 3, 4];
let (a, b) = v.split_at_mut(2);
a[0] = 10;
b[0] = 30;
println!("{:?}", v);
}This prints [10, 2, 30, 4]. Its implementation uses unsafe internally, wrapped in a safe interface. Related helpers include chunks_mut, split_first_mut, and iter_mut.
Bounds and panics
Slicing checks bounds at run time. A range that reaches past the end, or whose start is greater than its end, panics:
fn main() {
let v = vec![1, 2, 3];
let r = v.get(1..10);
println!("{:?}", r);
// &v[1..10] would panic: range end index 10 out of range
}Here get returns None instead of panicking. Use get when the range comes from user input or other untrusted data. Use direct indexing when an out-of-range value would be a bug in your own code and a panic is the right response.
Common mistakes
- Slicing strings by character count.
&s[0..3]means three bytes. Usechars().take(3)or checkis_char_boundaryfor text that may not be ASCII. - Holding a slice across a mutation. Any method taking
&mut selfon the owner conflicts with a live slice. Finish using the slice first, or copy the data you need (to_vec(),to_string()). - Returning a slice of a local. A slice of a local
StringorVecdangles once the function returns, so the compiler rejects it. Return the owned value instead. - Expecting a slice to grow. A slice has a fixed length. To add elements you need the owning
VecorString.
Summary of the model
- A slice is a pointer plus a length, borrowing a contiguous part of an owner.
&strand&[T]are shared slices.&mut [T]allows changing elements but not the length.- Slices follow the same borrowing rules as other references, so mutating the owner while a slice is live is a compile error.
- Range indexing panics on bad bounds or non-character boundaries.
getreturns anOptioninstead. - Accept
&strand&[T]in parameters unless you need the owning type.
Exercise
Why does this code fail to compile, and how do you fix it without cloning? fn main() { let mut v = vec![1, 2, 3]; let tail = &v[1..]; v.push(4); println!("{:?}", tail); }
Show answer
tail is a shared borrow of v that is still used by the println! after v.push(4) needs a mutable borrow, which gives error E0502. Fix it by moving the println! before the push, so the borrow ends after its last use. Then v.push(4) runs with no live slice. The program compiles and prints [2, 3].
Exercise
You need to write fn total(items: ???) -> i32 that sums integers and must work for a Vec<i32>, an array [i32; 3], and part of a vector. What parameter type do you choose, and why not &Vec<i32>?
Show answer
Use &[i32]. A &Vec<i32> parameter accepts only a vector, while &[i32] accepts a &Vec<i32> through deref coercion, an array through unsizing coercion, and any sub-slice such as &v[1..3].