Sub topic 16
When an array is not enough: Vec
This chapter assumes you know how to declare arrays and slices, how &[T] borrowing works, and how to run programs with cargo. It covers the standard library type you reach for when the number of elements is not known until the program runs.
The limit of arrays
The length of an array is part of its type. [i32; 3] and [i32; 4] are different types, and the length must be known at compile time. That is a good fit for the days of the week or the corners of a rectangle. It is a poor fit for lines read from a file, items a user adds, or results from a search.
Vec<T> (pronounced "vec") is a growable, heap-allocated sequence of values of one type. Its length is a runtime value, and it can change.
Creating and changing a Vec
fn main() {
let mut scores: Vec<u32> = Vec::new();
scores.push(90);
scores.push(72);
scores.push(85);
println!("{:?} len={}", scores, scores.len());
println!("{:?}", scores.pop());
println!("{:?}", scores.get(5));
let zeros = vec![0u8; 4];
let listed = vec![1, 2, 3];
let from_array = Vec::from([10, 20, 30]);
println!("{:?} {:?} {:?}", zeros, listed, from_array);
let mut roomy: Vec<i32> = Vec::with_capacity(10);
roomy.extend([1, 2, 3]);
roomy.insert(0, 99);
roomy.remove(1);
println!("{:?} {}", roomy, roomy.capacity() >= 10);
}Points to notice:
vec![...]is a macro.vec![value; n]mirrors the array form[value; n], except thatncan be a runtime value.popreturnsOption<T>, because the Vec may be empty.getreturnsNonefor an index out of range, as it does on arrays.v[i]still panics wheniis out of range, exactly as with arrays.insertandremovein the middle shift every later element. They take time proportional to the number of elements moved.pushandpopat the end are cheap on average.with_capacity(n)reserves room for at leastnelements so that early pushes do not reallocate. It does not change the length.
What a Vec looks like in memory
A Vec value is a small fixed-size record on the stack with three fields: a pointer to the elements, a length, and a capacity. The elements live in one contiguous block on the heap. When a push would exceed the capacity, the Vec allocates a larger block, moves the elements over, and frees the old block. The growth strategy is an implementation detail, so do not depend on specific capacity numbers.
use std::mem::size_of;
fn main() {
println!("array: {} bytes", size_of::<[i32; 1000]>());
println!("vec: {} bytes", size_of::<Vec<i32>>());
}The array reports 4000 bytes because it holds all its elements inline. The Vec reports the size of its three fields, typically 24 bytes on a 64-bit target, no matter how many elements it holds. The exact number is not guaranteed by the language.
Vec and slices work together
A Vec<T> dereferences to a slice [T]. Because of this, &vec can be passed anywhere &[T] is expected, and every slice method (len, iter, contains, first, pattern matching) works on a Vec. This is why the previous chapter recommended writing functions that take &[T].
fn total(values: &[i32]) -> i32 {
values.iter().sum()
}
fn main() {
let array = [1, 2, 3];
let vector = vec![4, 5, 6];
println!("{}", total(&array));
println!("{}", total(&vector));
println!("{}", total(&vector[1..]));
let copy: Vec<i32> = array[..2].to_vec();
println!("{:?}", copy);
let back: [i32; 3] = vector.try_into().unwrap();
println!("{:?}", back);
let wrong: Result<[i32; 4], Vec<i32>> = copy.try_into();
println!("{:?}", wrong);
}Conversions between the types:
| From | To | How | Cost |
|---|---|---|---|
| `[T; N]` | `Vec<T>` | `Vec::from(array)` or `array.to_vec()` | Allocates and moves or copies elements |
| `&[T]` | `Vec<T>` | `slice.to_vec()` (needs `T: Clone`) | Allocates and clones elements |
| `Vec<T>` | `[T; N]` | `vec.try_into()` | Fails with the Vec returned if the length is not `N` |
| `Vec<T>` | `&[T]` | `&vec` or `vec.as_slice()` | Free |
A failed try_into gives the original Vec back in the Err, so no data is lost. The last two lines of main show that: a Vec of length 2 cannot become [i32; 4].
Mistakes to expect
Holding a reference across a push
A push can reallocate the heap block, which would leave any reference to an old element pointing at freed memory. The borrow checker rejects this at compile time.
fn main() {
let mut v = vec![1, 2, 3];
let first = v[0];
v.push(4);
println!("{first} {:?}", v);
}This version copies the first element, so nothing is borrowed when push runs. If you write let first = &v[0]; and then use first after v.push(4), the compiler reports error E0502, because v is borrowed immutably and mutably at once.
Indexing with the wrong type
Indexes are usize. A counter declared as i32 must be converted, or declared as usize from the start.
Removing elements while looping
You cannot call v.remove(i) while iterating over &v. Use v.retain(|x| ...) to keep elements that match a condition, or v.drain(..) to take elements out.
Using a Vec where an array is enough
Every Vec costs a heap allocation and an extra indirection. For a small collection whose length never changes, an array is simpler and keeps the data on the stack. Do not default to Vec when the length is fixed.
Deciding between the types
| Type | Length | Where elements live | Use when |
|---|---|---|---|
| Tuple `(A, B)` | Fixed, types may differ | Inline | A few values of different types, such as a function returning a result and a status |
| Array `[T; N]` | Fixed at compile time | Inline (often the stack) | Same-type values with a known count |
| Slice `&[T]` | Known at runtime, cannot change | Borrowed from elsewhere | Function parameters that only read or modify in place |
| `Vec<T>` | Changes at runtime | Heap | Count unknown in advance, or the collection grows and shrinks |
Exercise
A function must read numbers from a list whose size is only known at runtime, add a computed value to the end, and let a second function print the result without taking ownership. Which types do you use for the list and for the second function's parameter?
Show answer
Use Vec<i32> (or another element type) for the list, because its length changes at runtime and push adds the value. The second function takes &[i32], so it borrows the data, and the caller can pass &vec through deref coercion.
Exercise
What does this program print, and why? let v = vec![1, 2, 3]; let r: Result<[i32; 2], Vec<i32>> = v.try_into(); println!("{:?}", r);
Show answer
It prints Err([1, 2, 3]). The Vec has three elements and the target array has two, so the conversion fails. The error value is the original Vec, returned unchanged.