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()); // 5

Use 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 length

Use vectors for most collections — they’re the default go-to.

Iterating

for item in &arr { println!("{item}"); }
for item in &v   { println!("{item}"); }

Comparison

ArrayVector
SizeFixed at compile timeDynamic at runtime
Stored onStackHeap
Type[T; N]Vec<T>
When to useSize known, rarely changesMost other cases

In practice, you’ll use Vec the vast majority of the time.