Slices
A slice &[T] is a borrowed view of a contiguous run of elements. It is a pointer plus a length, and it is the type you want for "read these items" regardless of whether they live in a Vec or an array.
Detailed Explanation
&[T] does not own anything. It points at memory someone else owns: a Vec, an array, another slice, or a static. The length travels with the pointer, so a slice is two words. &mut [T] is the writable view, and it is exclusive — no other borrow of those elements may exist at the same time.
Functions that take &[T] accept a Vec (via deref), an array (&arr[..] or &arr), and a subrange v[a..b]. That is why a slice is a better parameter than &Vec<T>. &Vec<T> rejects arrays and already-sliced views. impl AsRef<[T]> is the generic form when you also want owned values that can present a slice.
Slicing is range syntax. v[a..b] is exclusive on b. v[a..=b] includes b. v[..] is the whole thing. A bad range panics. v.get(a..b) returns Option<&[T]> and is the fallible form. Slices can be split: split_at, split_first, chunks, windows. windows(n) is the sliding window of length n. chunks_exact is the batching iterator.
A slice of u8 is the binary cousin of &str. &str is a slice of bytes that is UTF-8. You can go s.as_bytes() from &str to &[u8] always, and std::str::from_utf8 the other way when you must check.
Fat pointers mean size_of::<&[T]>() is twice size_of::<&T>() for sized T. Passing a slice by value of the reference is still cheap: two words. Cloning a slice does not clone the elements; it copies the pointer and length. Cloning the elements is .to_vec().
When you take &[T]: read-only access to a run of items. When you take &mut [T]: in-place update of a run. When you take Vec<T>: you need to grow or keep the data.
Code Examples
fn sum(xs: &[i32]) -> i32 {
xs.iter().sum()
}
fn main() {
let v = vec![1, 2, 3, 4];
println!("{}", sum(&v)); // prints: 10
println!("{}", sum(&v[1..3])); // prints: 5
let windows: Vec<_> = v.windows(2).collect();
println!("{:?}", windows); // prints: [[1, 2], [2, 3], [3, 4]]
}Common Gotchas
A bad range panics
`v[0..9]` on a 3-element slice is a panic. Use `get` when the bounds come from outside.
`&Vec<T>` is a worse parameter than `&[T]`
You reject arrays and subslices for no gain. Take the slice.
`..` excludes the end
`v[0..1]` is one element. `v[0..=1]` is two. Off-by-one bugs hide here.
Cloning a slice is a pointer copy
`.clone()` on `&[T]` does not clone `T`. Call `.to_vec()` when you need owned elements.