Sub topic 2
What a slice is
This chapter assumes you know basic Rust syntax, ownership and moves, the basics of borrowing, and how arrays and Vec<T> work. It introduces the slice type &[T] and the idea that a slice is a borrowed view of data that something else owns.
The problem slices solve
An array [i32; 5] has its length in its type. A Vec<i32> owns a growable heap buffer. Both store elements next to each other in memory. Often a function only needs to read some of those elements and does not care who owns them or how many there are.
A slice is a reference to a contiguous run of elements. It does not own the elements and does not copy them. Its type is written &[T], or &mut [T] when you may change the elements.
fn main() {
let a = [10, 20, 30, 40, 50];
let s = &a[1..4];
println!("{:?} len={}", s, s.len());
}This prints [20, 30, 40] len=3. The expression a[1..4] names elements 1, 2 and 3. The & in front borrows them, and the result has type &[i32].
Array, Vec and slice compared
These three types are easy to confuse. The table shows how they differ.
| Type | Owns its data | Length known | Where the length lives |
|---|---|---|---|
| `[i32; 5]` | Yes | At compile time | In the type |
| `Vec<i32>` | Yes | At run time, can change | In the Vec value |
| `&[i32]` | No | At run time, fixed | In the reference |
The key point is that the slice's length is part of the reference, not part of the type. Because of that, one slice type covers views of any length, and it works over arrays and vectors alike.
The slice stores only a pointer and a length. Nothing is copied, so creating a slice costs the same no matter how large the data is.
One function for many sources
The slice type lets you write a function once and call it with arrays, vectors, or parts of either.
fn sum(xs: &[i32]) -> i32 {
xs.iter().sum()
}
fn main() {
let arr = [1, 2, 3];
let v = vec![4, 5, 6];
println!("{}", sum(&arr));
println!("{}", sum(&v));
println!("{}", sum(&v[1..]));
}The output is 6, 15 and 11. Passing &arr works because Rust converts a reference to an array into a slice. Passing &v works because Vec<i32> dereferences to [i32]. The next chapters on function parameters cover this conversion in more detail.
What you can do with a slice
A slice has a length and supports indexing and iteration. These are the basic operations.
s.len()returns the number of elements.s.is_empty()tells you whether the length is zero.s[i]reads one element, and panics ifiis out of range.s.iter()yields references to each element.s.first()ands.last()return anOptionholding a reference.
A shared slice &[T] is read-only. A &mut [T] lets you assign to elements and call methods such as sort. It cannot change the length, because the slice does not own the buffer. Pushing and popping belong to Vec.
Common errors
Writing the bare type [T]. The type [i32] without a reference has no size known at compile time, so you cannot keep it in a local variable or pass it by value. You will nearly always see it behind a pointer: &[i32], &mut [i32], or Box<[i32]>.
Changing the owner while a slice exists. A slice borrows from its owner. Suppose you write let s = &v[..2]; and then call v.push(4) while s is still used later. The compiler rejects this with error E0502. The reason is that push may move the buffer, which would leave the slice pointing at freed memory. The borrow checker prevents that.
Expecting a copy. A slice does not duplicate the data. If you need an independent copy, call s.to_vec(), which allocates a new Vec.
Summary
A slice is a pointer plus a length, borrowed from an array, a vector, or another slice. It gives you a single type for read access to contiguous data. The following chapters show how to create slices with ranges and how to handle out-of-range access.
Exercise
Given let v = vec![5, 6, 7, 8]; and let s = &v[1..3];, what do s.len() and s[0] return, and does creating s copy any elements?
Show answer
s.len() is 2 and s[0] is 6, because the range 1..3 covers the elements at indexes 1 and 2. Creating s copies nothing. It stores only a pointer into v's buffer and a length.
Exercise
Why does fn total(xs: &[i32]) accept both &[1, 2, 3] (an array) and &vec (a Vec<i32>), while a function taking &Vec<i32> accepts only the second?
Show answer
Both an array reference and a &Vec<i32> convert automatically to &[i32]. A parameter of type &Vec<i32> requires an actual vector, so an array is rejected. Taking &[i32] makes the function more general and gives up nothing.