Skip to main content

Vectors: the growable list

`Vec<T>` is the workhorse collection: a growable, heap-allocated list of one type. `vec![]` builds one, `push` appends, and it frees itself when its owner goes out of scope.

Indexing with `[i]` panics when the index is out of range; `get(i)` returns an `Option` instead. Pick the one that matches how sure you are.

Iterating comes in three flavours and the difference is ownership: `iter()` borrows, `iter_mut()` borrows mutably, and `into_iter()` consumes the vector. The compiler stops you from mixing them by accident.

Pushing while iterating

fn main() {
    let mut items = vec![1, 2, 3];
    for item in &items {
        items.push(item * 2); // error[E0502]
    }
}

error[E0502]: cannot borrow `items` as mutable because it is also borrowed as immutable

Collect the new values into a separate `Vec` first, then `items.extend(new_values)` after the loop ends.

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust