Sub topic 13
Slices: borrowing a view of an array
This chapter assumes you can write array types such as [i32; 4], index arrays, and use & references. It builds on those to show how one function can accept many sequence types.
What a slice is
A slice is a view of a run of elements stored somewhere else. Its type is [T], and its length is not part of the type. You can't hold a [T] by value, so you always borrow it as &[T] or &mut [T]. That reference is a "fat pointer": it stores the address of the first element and the number of elements.
Creating slices
Apply a range to an array, a Vec, or another slice, then borrow the result.
| Expression | Elements covered |
|---|---|
| `&a[..]` | all |
| `&a[2..]` | index 2 to the end |
| `&a[..3]` | indices 0, 1, 2 |
| `&a[1..4]` | indices 1, 2, 3 |
| `&a[1..=3]` | indices 1, 2, 3 |
One function for many inputs
Declaring a parameter as &[i32] lets callers pass an array, part of an array, or a Vec.
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let array = [1, 2, 3, 1];
let vector = vec![4, 5, 6];
println!("{}", sum(&array));
println!("{}", sum(&array[1..3]));
println!("{}", sum(&vector));
}This prints 7, 5, and 15. The compiler converts &[i32; 4] to &[i32] automatically, and &Vec<i32> to &[i32] through deref coercion. Prefer &[T] over &[T; N] or &Vec<T> in function parameters unless you need the exact type.
Mutable slices
A &mut [T] lets a function change elements in place. It can't change the length.
fn double(values: &mut [i32]) {
for v in values.iter_mut() {
*v *= 2;
}
}
fn main() {
let mut a = [1, 2, 3, 4, 5];
double(&mut a[..3]);
println!("{:?}", a);
}This prints [2, 4, 6, 4, 5]. Only the first three elements changed.
Common errors
Slicing checks the range at run time. A range that ends past the length, or starts after its end, panics.
fn main() {
let a = [1, 2, 3];
println!("{:?}", a.get(1..9));
println!("{:?}", a.get(1..3));
}This prints None, then Some([2, 3]). Use get with a range when the bounds come from input you don't control.
Slice indexes count elements, not bytes, for [T]. Slicing a str is different: its ranges are byte offsets and must fall on character boundaries.
Exercise
Write a function middle(values: &[i32]) -> &[i32] that returns everything except the first and last elements. It should return an empty slice if there are fewer than three elements. Which method or range lets you avoid a panic?
Show answer
fn middle(values: &[i32]) -> &[i32] { if values.len() < 3 { &[] } else { &values[1..values.len() - 1] } } The length check prevents a panic. Alternatively, values.get(1..values.len().saturatingsub(1)).unwrapor(&[]) returns an empty slice when the range is invalid.