Answer#
Use a Vec<T> when the number of items is not known until the program runs or changes. Use an array [T; N] when the length is a fixed fact, such as 12 months. Use &[T] for parameters: it is a pointer and a length, and borrowing it copies nothing.
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let array: [i32; 3] = [1, 2, 3]; // fixed length, part of the type
let mut vec: Vec<i32> = vec![1, 2, 3]; // growable, on the heap
vec.push(4);
let slice: &[i32] = &vec[1..3]; // a borrowed window onto either
println!("{} {} {}", sum(&array), sum(&vec), sum(slice));
println!("{array:?} {vec:?} {slice:?}");
println!("{} {} {}", array.len(), vec.len(), slice.len());
}6 10 5
[1, 2, 3] [1, 2, 3, 4] [2, 3]
3 4 2Why it works#
&vec and &array convert to &[i32] automatically, so sum is written once and works with both. A slice made with &vec[1..3] holds items 1 and 2: the end is not included. Taking a slice while you still hold it prevents the original from being changed, which is the borrow checker protecting you from a Vec that moves its items when it grows.
Common mistakes#
- Writing a parameter as
&Vec<T>. Clippy warns about it (ptr_arg), and&[T]accepts more callers. - Indexing past the end.
v[10]on a three-item list panics at run time.v.get(10)returnsNoneinstead. - Expecting
let a = [0; 100_000_000]to be cheap. Arrays live where they are declared (usually the stack); big buffers belong in aVec.
Related questions#
How do I make a Vec with a starting size?#
vec![0; 5] gives five zeros, and Vec::with_capacity(n) reserves room for n items without adding any.