Sub topic 16
When an array is not enough: Vec
This chapter assumes you know array types like [T; N], indexing, and borrowing a slice with &[T].
The limit of an array
An array's length is part of its type, so [i32; 3] and [i32; 4] are different types. The length must be known at compile time and never changes. That suits a fixed grid or a table of constants. It does not suit data whose size depends on the program's input, such as lines read from a file or search results.
A Vec<T> (a vector) is a growable list of values of one type. Its elements live on the heap, which is memory the program requests while it runs. The Vec value itself is small. It holds a pointer to that memory, a length, and a capacity (how many elements fit before it must allocate again).
Creating and growing a Vec
fn sum(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let mut numbers = Vec::new();
numbers.push(3);
numbers.push(1);
numbers.push(4);
println!("{:?} len={}", numbers, numbers.len());
let last = numbers.pop();
println!("{:?} {:?}", last, numbers);
let zeros = vec![0; 3];
let from_array = Vec::from([7, 8, 9]);
println!("{:?} {:?}", zeros, from_array);
println!("{}", sum(&numbers));
println!("{}", sum(&from_array));
}Vec::new() makes an empty vector, and the compiler infers the element type from later use. The vec![value; n] macro mirrors the array form [value; N], except that n can be a runtime value. pop returns an Option, because an empty vector has nothing to remove.
The sum function takes &[i32], so it accepts a reference to a Vec without any conversion. A &Vec<i32> is automatically treated as a slice. This is why functions should take slices and not &Vec<T> or &[T; N].
Arrays and Vec compared
| Property | Array `[T; N]` | `Vec<T>` |
|---|---|---|
| Length | Fixed, part of the type | Changes at run time |
| Storage | Inline (the stack, if it is a local variable) | Elements on the heap |
| Add or remove items | No | `push`, `pop`, `insert`, `remove` |
| Borrow as slice | `&array` | `&vec` |
Growing a vector can move its elements to a larger heap block. If you know the size in advance, Vec::with_capacity(n) reserves space once and avoids repeated reallocation.
Common mistake: borrowing while pushing
fn main() {
let mut v = vec![1, 2, 3];
let first = &v[0];
v.push(4); // error: cannot borrow `v` as mutable
println!("{first}");
}This does not compile. push may reallocate and move the elements, which would leave first pointing at freed memory. The borrow checker rejects it. Finish using the reference before you push, or copy the value out with let first = v[0];.
Exercise
You read numbers from the user until they type "done", then print their total. Should you store them in an array or a Vec, and what should the printing function's parameter type be?
Show answer
Use a Vec, because the count is unknown until run time and the program must push each new number. The function should take &[i32] (or the matching element type), so it works with a Vec, an array, or part of either.