Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Collections

Rust Vec<T> type

Reference for Rust Vec<T>: creating vectors, indexing, pushing and popping, iteration, capacity, slices, ownership rules and common panics.

Vec<T> is Rust's growable, heap-allocated array. It owns a contiguous buffer of T values and tracks three things: a pointer to the buffer, its length (how many elements are in use) and its capacity (how many fit before it must reallocate). Elements are stored next to each other, so indexing is O(1) and iteration is cache friendly.

A vector dereferences to a slice, so every slice method (len, iter, sort, contains, windows and many more) works on a Vec<T> directly. Add or remove elements at the end cheaply; adding or removing near the front is O(n) because later elements shift.

Rust
let mut v: Vec<i32> = Vec::new();
v.push(1);
let w = vec![1, 2, 3];

Try it

Rust Creating and using a vector

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Ownership and an out-of-bounds panic

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
pub struct Vec<T, A: Allocator = Global> { /* private */ }

Vec::new() -> Vec<T>
Vec::with_capacity(capacity: usize) -> Vec<T>
vec![a, b, c]            // from elements
vec![value; n]           // n clones of value
v[i]                     // index (panics when out of range)
v.get(i) -> Option<&T>
Name Description
T The element type. All elements share it. It does not need to be Copy or Clone for most operations.
capacity Number of elements to reserve space for up front. The length stays 0.
i A usize position, counted from 0.

Returns: Vec::new never allocates; the first push does. with_capacity allocates once. vec![value; n] requires T: Clone.

Panics and edge cases: v[i] panics when i >= len. A capacity larger than isize::MAX bytes panics with "capacity overflow". Zero-sized types such as Vec<()> never allocate, and their capacity reads as usize::MAX.

Usage notes

  • Prefer get for untrusted indexes. It returns None instead of panicking. Plain indexing is right when an invalid index is a bug.
  • Borrowing is strict. While you hold &v[0] or an iterator, you cannot call push, because it may reallocate and invalidate the reference. The compiler rejects such code.
  • Three ways to loop: for x in &v (shared), for x in &mut v (mutable) and for x in v (consumes v). See IntoIterator.
  • Growth is amortized O(1). The capacity grows geometrically, so n pushes cost O(n) overall. If you know the size, with_capacity avoids reallocations.
  • Cloning copies every element. Pass &[T] to functions that only read; accept Vec<T> only when you need to own or grow it.
  • Comparisons are element-wise, and Vec<T> implements Ord, Hash and Default when T does.
  • Insert and remove in the middle are O(n). If order does not matter, swap_remove is O(1). For queues use VecDeque.
  • Convert freely: Vec<T> from an array with Vec::from([1, 2]), to a boxed slice with into_boxed_slice, and from an iterator with collect().