Sub topic 13
Slices: borrowing a view of an array
This chapter assumes you can write functions in Rust, know the [T; N] array type, and understand shared (&) and mutable (&mut) references. It builds on array indexing and get. It leads into slice patterns and the choice between array, slice, and Vec.
What a slice is
A slice is a view of a run of elements stored somewhere else. The type [T] means "some number of T values in a row", where the number is not known at compile time. Because its size is unknown, you never hold a [T] directly. You hold a reference to it: &[T] for read access, or &mut [T] for read and write access.
A &[T] is a fat pointer made of two words: the address of the first element and the element count. On a 64-bit target that is 16 bytes. The slice owns nothing. It borrows from an array, a Vec, or any other contiguous storage, so the borrow checker applies the usual rules to it.
Creating slices
You make a slice by borrowing a range of a collection. Ranges count elements, and usize values select them.
| Expression | Elements selected |
|---|---|
| `&a[1..4]` | indices 1, 2, 3 |
| `&a[..4]` | indices 0 through 3 |
| `&a[1..]` | index 1 to the end |
| `&a[1..=3]` | indices 1, 2, 3 (inclusive end) |
| `&a[..]` | everything |
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let array = [10, 20, 30, 40, 50];
let vector = vec![1, 2, 3];
let middle = &array[1..4];
println!("{:?} len={}", middle, middle.len());
println!("{}", sum(&array));
println!("{}", sum(middle));
println!("{}", sum(&vector));
println!("{}", sum(&vector[..2]));
println!("{}", sum(&array[..]));
}This prints [20, 30, 40] len=3, then 150, 90, 6, 3, and 150.
sum(&array) passes a &[i32; 5], yet the parameter is &[i32]. Rust converts the array reference to a slice automatically, which is an unsized coercion. &vector is a &Vec<i32>, and deref coercion turns it into &[i32]. Because of these coercions, a function that takes &[T] accepts arrays of any length, parts of arrays, and vectors. Prefer &[T] over &[T; N] or &Vec<T> in parameters unless you need the exact length or need to grow the vector.
Slices carry their length
Every slice knows its length, so len, is_empty, first, last, iter, contains, windows, and chunks all work on &[T]. Most "array methods" are really slice methods that arrays reach through the same coercion.
fn main() {
let data = [3, 8, 1, 9, 4, 7];
let s = &data[..];
println!("{:?} {:?}", s.first(), s.last());
println!("{}", s.contains(&9));
for pair in s.windows(2) {
print!("{} ", pair[1] - pair[0]);
}
println!();
for chunk in s.chunks(4) {
println!("{:?}", chunk);
}
}windows(2) yields overlapping pairs, so the differences printed are 5 -7 8 -5 3. chunks(4) yields [3, 8, 1, 9] and then the shorter final chunk [4, 7]. Keep this in mind: the last chunk may be shorter than requested.
Out-of-range slicing
Indexing a slice with a range checks the range at run time. These cases panic:
- The end is greater than the length.
- The start is greater than the end.
- An inclusive range ends at
usize::MAX.
When the range comes from input you do not control, call get with a range. It returns Option<&[T]> and gives None instead of panicking.
fn main() {
let data = [1, 2, 3, 4];
println!("{:?}", data.get(1..3));
println!("{:?}", data.get(2..9));
println!("{:?}", data.get(3..2));
println!("{:?}", data.get(4..));
}The output is Some([2, 3]), None, None, and Some([]). A start equal to the length is valid and gives an empty slice. A start past the length is not.
Mutable slices
A &mut [T] lets a function change elements in place but not change the length. That fixed length is why the same function can work on an array or a Vec.
fn zero_first(values: &mut [i32]) {
if let Some(first) = values.first_mut() {
*first = 0;
}
}
fn main() {
let mut data = [5, 6, 7, 8, 9];
zero_first(&mut data[2..]);
println!("{:?}", data);
let (left, right) = data.split_at_mut(2);
std::mem::swap(&mut left[0], &mut right[0]);
println!("{:?}", data);
}The first line prints [5, 6, 0, 8, 9]. The second prints [0, 6, 5, 8, 9].
split_at_mut exists because the borrow checker cannot prove that &mut data[..2] and &mut data[2..] do not overlap. Two separate range borrows in one scope are rejected. split_at_mut splits at one index and returns two disjoint halves.
Common errors
Mutating while a slice is alive. A slice holds a borrow of its source for as long as the slice is used.
fn main() {
let mut data = vec![1, 2, 3];
let head = &data[..2];
data.push(4); // error[E0502]: cannot borrow `data` as mutable
println!("{:?}", head);
}push might reallocate the buffer and leave head pointing at freed memory. The compiler stops this. Finish using the slice before changing the owner, or copy the data out with to_vec().
Expecting a slice to be an array. A &[i32] has no length in its type, so you cannot pass it where [i32; 3] is required. Convert with try_into, which checks the length: let a: [i32; 3] = slice.try_into().unwrap();. The const generics chapter covers this fully.
Returning a slice of a local. A function cannot return &local_array[..], because the array is dropped when the function ends. Return the owned value, or return a slice of a parameter, which keeps that parameter's lifetime.
Using [T] by value. Writing fn f(x: [i32]) fails because the size is unknown. Always put the reference in the type.
Practice
Exercise
What does data.get(2..2) return for let data = [1, 2, 3, 4];, and why does &data[2..2] not panic?
Show answer
Both give an empty slice (Some([]) for get). A range whose start equals its end is valid as long as the start does not exceed the length. Only a start greater than the end, or an end greater than the length, is out of range.
Exercise
Why does this fail to compile, and how would you fix it? let mut data = [1, 2, 3, 4]; let a = &mut data[..2]; let b = &mut data[2..]; a[0] = b[0];
Show answer
The borrow checker sees two overlapping mutable borrows of data, since it cannot reason about the ranges. Use let (a, b) = data.split_at_mut(2);, which returns two disjoint &mut [i32] halves that can be used together.