Vec & Slices
Vec<T> owns a growable buffer. &[T] borrows a contiguous view into Vec, arrays, or other data.
Search across all documentation pages
Vec<T> owns a growable buffer. &[T] borrows a contiguous view into Vec, arrays, or other data.
fn sum(slice: &[i32]) -> i32 {
slice.iter().sum()
}
fn main() {
let v = vec![1, 2, 3];
println!("{}", sum(&v));
println!("{:?}", &v[1..]);
}When to reach for this: Default dynamic array; expose &[T] in read APIs.
fn dedup_sorted(v: &mut Vec<i32>) {
v.sort_unstable();
v.dedup();
}
fn main() {
let mut data = vec![3, 1, 2, 2, 3];
dedup_sorted(&mut data);
println!("{:?}", data);
}What this demonstrates:
sort_unstable + dedup in-placeVec passed by &mut&v[1..] shares backing bufferlen, capacity, reserve, shrink_to_fit, split_at, windows, chunks. Vec deref coerces to [T].
v[i] out of bounds. Fix: get(i).retain.shrink_to_fit after large temp build.Vec<()> odd capacity behavior - edge case.| Alternative | Use When | Don't Use When |
|---|---|---|
SmallVec | Usually small | Always heap ok |
ArrayVec | Fixed max, stack | Unbounded growth |
Box<[T]> | Immutable sized slice owned | Need push |
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Reviewed by Chris St. John·Last updated Jul 16, 2026