skip to content

Vec and Arrays

[T; N] has a fixed length known at compile time and is stored inline, Vec<T> grows on the heap. Interviewers ask about capacity, reallocation and why a reference into a Vec blocks a push.

on this pageshow

questions

4

In Rust, when should a value be a fixed `[f32; 3]` array rather than a `Vec<f32>`, and what does each one cost?

level: juniorimportance: must knowfreq 72%

answer

  1. length lives in the type
  2. inline storage vs heap buffer
  3. Copy when the element is Copy
  4. pointer, capacity, length triplet

basics

~20 s

A [f32; 3] stores exactly three floats inline, with the length fixed in its type and no allocation; a Vec<f32> is a pointer, capacity and length pointing at a heap buffer that can grow at run time.

solid answer

~50 s

`[T; N]` is a value whose length `N` is part of its type: it is stored inline wherever its owner lives (on the stack for a local), never allocates, and is `Copy` when `T` is `Copy`. A `[f32; 3]` position is 12 bytes, and assigning a `[f32; 2]` to it is a type error (E0308). `Vec<T>` is a (pointer, capacity, length) triplet that owns a heap buffer, grows with `push`, and is never `Copy`; cloning it allocates. So a fixed-size thing such as a 3D position, an RGB colour or a hash digest is an array, and a collection whose size is known only at run time, such as an incoming stream of samples, is a `Vec`. The two combine well: `Vec<[f32; 3]>` is one contiguous buffer of 12-byte points, where `Vec<Vec<f32>>` would be one allocation per point.

code

rust · 22 lines
rust
#[derive(Debug, Clone, Copy, PartialEq, Default)]
struct Position([f32; 3]);

fn main() {
    let p = Position([1.0, 2.0, 3.0]);
    let q = p; // [f32; 3] is Copy, so Position can be Copy too
    println!("{:?} {:?} size = {} bytes", p, q, std::mem::size_of::<Position>());

    // One heap buffer holding 12 bytes per point, contiguous
    let mut path: Vec<[f32; 3]> = Vec::with_capacity(2);
    path.push(p.0);
    path.push([4.0, 5.0, 6.0]);
    path.push([7.0, 8.0, 9.0]);
    println!("len = {}, capacity = {}", path.len(), path.capacity());

    // Runtime length back into a compile-time length: checked
    let v = vec![0.5_f32, 0.25, 0.125];
    let arr: [f32; 3] = v.try_into().expect("exactly three");
    println!("{:?} {:?}", arr, Position::default());
    let short: Result<[f32; 3], _> = vec![1.0_f32, 2.0].try_into();
    println!("{:?}", short.is_err());
}

go deeper

for a junior

Say that an array's length is part of its type and never changes, while a Vec grows on the heap. Give one fixed-shape example, such as a 3D position.

for a middle

Explain inline storage versus the pointer, capacity and length header, why arrays are Copy when their element is and Vec never is, and how try_into converts at a checked boundary.

for a senior

Point out layout consequences in real code: Vec of arrays is one contiguous buffer while Vec of Vecs is an allocation per row, and huge local arrays risk stack overflow.

for a principal

Frame it as making the data's shape explicit in types: fixed-length data in arrays lets the compiler reject wrong lengths and keeps hot loops free of extra allocations.

## Two different kinds of value Rust has two owned sequence types that beginners often confuse. - **`[T; N]`, the array**: exactly `N` values of type `T`, laid out one after another. `N` is a compile-time constant and is **part of the type**, so `[f32; 3]` and `[f32; 4]` are different types. - **`Vec<T>`, the vector**: a growable sequence. The `Vec` value itself is a small header, guaranteed by the standard library to be a **(pointer, capacity, length) triplet**, and the elements live in a **heap buffer** that the vector owns and frees when it is dropped. An array has no header and no buffer: the elements *are* the value. A local `[f32; 3]` sits on the stack; the same array as a struct field lives inside that struct, and inside a `Vec` it lives in the vector's heap buffer. "Arrays live on the stack" is only true of arrays held in locals. ## What the type system does with the length Because the length is in the type, rustc checks it at compile time: ```rust let a: [f32; 3] = [1.0, 2.0]; // error[E0308]: mismatched types ``` The compiler reports "expected an array with a size of 3, found one with a size of 2". There is no `push` on an array and no way to change its length. A `Vec<f32>` carries its length at run time, so `v.len()` can be anything and the compiler cannot know it. This makes arrays the natural choice for **fixed-shape data**: 1. a 3D position or velocity, `[f32; 3]`; 2. an RGBA colour, `[u8; 4]`; 3. a SHA-256 digest, `[u8; 32]`; 4. a small lookup table whose size is part of the design. ## Copying, cloning and traits The standard library implements `Copy` for `[T; N]` whenever `T: Copy`, and `Clone` whenever `T: Clone`. A `struct Position([f32; 3])` can therefore `#[derive(Clone, Copy)]`, and passing it by value is a 12-byte memory copy with the original still usable. `Default` is implemented for arrays only up to length 32, a historical limit that still stands. `Vec<T>` is never `Copy`, because it owns a heap allocation: a bitwise copy would give two owners of one buffer. Moving a `Vec` copies only its three-word header; `clone()` allocates a new buffer and clones every element. | | `[T; N]` | `Vec<T>` | |---|---|---| | Length | fixed, in the type | run time, changes with `push` and `pop` | | Storage | inline in its owner | heap buffer owned by the header | | Allocation | never | on growth; `Vec::new()` does not allocate until elements are pushed | | `Copy` | when `T: Copy` | never | | Size of the value | `N * size_of::<T>()` | three words | ## Converting between them - `vec![1.0, 2.0, 3.0]` or `Vec::from([1.0, 2.0, 3.0])` turns an array into a vector. - `let arr: [f32; 3] = v.try_into()` turns a vector into an array; it returns `Err` holding the original vector when the length is not exactly 3, so the run-time length is checked at the boundary. - Both coerce to a slice `&[T]`, which is how functions usually accept either; slices themselves are covered with borrowing. ## Combining them A common pattern in game and simulation code is `Vec<[f32; 3]>`: one heap buffer holding points back to back, 12 bytes each, iterated with no pointer chasing. The alternative `Vec<Vec<f32>>` makes every point a separate heap allocation with its own three-word header, wastes memory and scatters the data. When every inner sequence has the same known length, the array is both cheaper and more honest about the shape. ## Pitfalls - A **very large array** in a local can overflow the thread's stack, since the whole array is the local; the lesson on `Box` covers heap-allocating such buffers. - `[x; N]` repeat syntax needs `x` to be `Copy` or a constant; `vec![x; n]` needs `Clone` and takes `n` at run time. - An array whose length differs per call site is not a fit for `[T; N]` unless the code is generic over `const N: usize`, which the lesson on const generics covers. The rule of thumb an interviewer wants to hear: **length known when you write the code, use an array; length known only when the program runs, use a `Vec`.**

  • In Rust, why can `#[derive(Copy)]` be applied to a struct holding `[f32; 3]` but not to one holding `Vec<f32>`?
    `Copy` means a bitwise copy is a complete, independent duplicate. `[f32; 3]` is just three floats, and the standard library implements `Copy` for `[T; N]` when `T: Copy`. A `Vec<f32>` owns a heap buffer and implements `Drop`; a bitwise copy would create two owners that both free the same buffer, so `Vec` is only `Clone`, which allocates a fresh buffer.
  • In Rust, how do you turn a `Vec<f32>` of run-time length into a `[f32; 3]`, and what happens if the length is wrong?
    Use `TryFrom`: `let arr: [f32; 3] = v.try_into()`. It succeeds only when the length is exactly 3 and returns `Err` carrying the original vector otherwise, so no data is lost and no panic happens unless you call `unwrap` or `expect` on the result.

  • Arrays always live on the stack, wherever they are stored
  • A [f32; 3] can be pushed to once it needs a fourth element
  • Vec<f32> is Copy because f32 is Copy
  • Vec<Vec<f32>> is as compact as Vec<[f32; 3]> for fixed-size points
  • Vec::new() allocates a buffer immediately
open as a page

For a Rust `Vec<T>`, how do `len` and `capacity` differ, and when do `with_capacity`, `reserve` and `shrink_to_fit` pay off?

level: middleimportance: must knowfreq 66%

basics

~20 s

len counts the elements a Vec holds; capacity counts the slots its buffer has room for. A push reallocates, possibly moving the buffer, only when len equals capacity, and a Vec never shrinks on its own: shrink_to_fit or shrink_to returns the memory.

open as a page

When compacting a Rust `Vec<T>` buffer in place, when do you reach for `drain`, `retain`, `dedup`, `extract_if` or `swap_remove`?

level: middleimportance: should knowfreq 48%

basics

~10 s

drain(range) removes a range and yields it; retain keeps what a predicate accepts; dedup removes consecutive duplicates; extract_if (Rust 1.87) removes and yields predicate matches; swap_remove removes one element in O(1) by breaking order.

open as a page

In Rust, when do you pick `sort` over `sort_unstable` for a `Vec<T>`, and why does `values.sort()` on a `Vec<f32>` fail with E0277?

level: seniorimportance: should knowfreq 42%

basics

~20 s

sort is stable and may allocate a scratch buffer; sort_unstable may reorder equal elements but sorts in place without allocating. Both need T: Ord, which f32 lacks because NaN breaks total order, so float vectors use sort_by(f32::total_cmp).

open as a page