title: Arrays and Vectors
Arrays
Fixed size, stack allocated. Size must be known at compile time and cannot change.
let arr: [i32; 5] = [1, 2, 3, 4, 5]; // type is [T; N], size is part of the type
let zeros = [0; 10]; // ten zeros
println!("{}", arr[0]); // indexing
println!("{}", arr.len()); // 5Use arrays when you know the exact size upfront (e.g. days of the week, RGB values).
Vectors
Dynamic size, heap allocated. Can grow and shrink at runtime.
let mut v: Vec<i32> = Vec::new();
let v = vec![1, 2, 3, 4, 5]; // vec! macro is the common shorthand
v.push(6); // add to end
v.pop(); // remove from end, returns Option<T>
println!("{}", v[0]); // indexing (panics if out of bounds)
println!("{}", v.len()); // current lengthUse vectors for most collections — they’re the default go-to.
Iterating
for item in &arr { println!("{item}"); }
for item in &v { println!("{item}"); }Comparison
| Array | Vector | |
|---|---|---|
| Size | Fixed at compile time | Dynamic at runtime |
| Stored on | Stack | Heap |
| Type | [T; N] | Vec<T> |
| When to use | Size known, rarely changes | Most other cases |
In practice, you’ll use Vec the vast majority of the time.