Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Macros

Rust vec! macro

Reference for the Rust vec! macro: list and repeat forms, how the repeat form clones values, capacity, nested vectors and common mistakes.

vec! builds a Vec<T> from a list of elements or from a value and a count. It is the usual way to write a vector literal, the way [1, 2, 3] writes an array. The elements live on the heap, and the vector can grow afterwards.

There are three forms: vec![] for an empty vector, vec![a, b, c] for a list, and vec![value; count] for count copies of value. The repeat form needs value to implement Clone.

Rust
let empty: Vec<i32> = vec![];
let list = vec![1, 2, 3];
let zeros = vec![0u8; 4];

Try it

Rust The three forms of vec!

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 Nested vectors and capacity

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
vec![]                 // Vec<T>, T inferred
vec![elem, elem, ...]  // from a list
vec![elem; n]          // n clones of elem (n: usize)
Name Description
elem An expression. In the list form every element must have the same type.
n A usize expression: how many elements to create.

Returns: a Vec<T>. Panics / edge cases: vec![x; n] panics if the allocation is too large (capacity overflow) and aborts if memory runs out. n may be 0, which gives an empty vector.

Usage notes

  • Repeat form clones. vec![elem; n] clones elem n - 1 times and moves the original into the last slot. For vec![Vec::new(); 3] that gives three independent empty vectors, not three handles to one.
  • Not shared. If you need shared mutable rows, use Rc<RefCell<...>> explicitly; vec! never aliases.
  • Type inference. vec![] needs a type from context (an annotation or a later use). vec![1, 2.5] fails because the elements disagree.
  • Capacity. The list form allocates exactly the number of elements, so the first push reallocates. Use Vec::with_capacity(n) if you will fill the vector gradually.
  • Array instead? For a fixed size known at compile time, [0; 4] is an array on the stack and needs no allocation.
  • Slices. vec![..] derefs to &[T], so you can pass &v to any function taking a slice.
  • Large zeroed vectors (vec![0; n]) are fast: for integers the allocator can hand back zeroed memory directly.