Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Collections

Rust Vec capacity and reserve

Reference for Vec::capacity, with_capacity, reserve, reserve_exact, shrink_to_fit and try_reserve in Rust: how growth works and when to preallocate.

A vector's length is how many elements it holds; its capacity is how many it can hold before it has to allocate a bigger buffer. The methods on this page let you inspect and steer that: capacity() reads it, with_capacity and reserve raise it ahead of time, and shrink_to_fit gives memory back.

Capacity is a performance tool, never a correctness one. A vector with spare capacity behaves exactly like one without; it just avoids copying its elements to a new buffer on growth.

Rust
let mut v: Vec<u32> = Vec::with_capacity(1000);
assert!(v.capacity() >= 1000 && v.is_empty());

Try it

Rust Watching capacity change

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 reserve and try_reserve

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
impl<T> Vec<T> {
    pub fn capacity(&self) -> usize;
    pub fn with_capacity(capacity: usize) -> Vec<T>;
    pub fn reserve(&mut self, additional: usize);
    pub fn reserve_exact(&mut self, additional: usize);
    pub fn try_reserve(&mut self, additional: usize) -> Result<(), TryReserveError>;
    pub fn shrink_to_fit(&mut self);
    pub fn shrink_to(&mut self, min_capacity: usize);
}
Name Description
additional How many more elements, beyond the current len, the vector should be able to hold without reallocating.
min_capacity For shrink_to, a lower bound the capacity will not go below.

Returns: capacity returns a usize. try_reserve returns Err(TryReserveError) on capacity overflow or when the allocator refuses.

Panics and aborts: reserve panics on capacity overflow and aborts the process if the allocator fails. Use try_reserve for untrusted sizes.

Usage notes

  • After reserve(n) the capacity is at least len + n, often more because the allocator may round up. reserve_exact asks for no extra slack, but still does not promise an exact number.
  • Growth is geometric. When a push finds the buffer full, the new capacity is at least double (with a small minimum). The exact sequence is not part of the contract, so never print or rely on it.
  • Preallocate when you know the size. Vec::with_capacity(n) before a loop of n pushes, or collect() from an iterator with a good size hint, avoids repeated copies.
  • Capacity is not length. Indexing past len panics even if capacity is large; the spare slots are uninitialized memory.
  • clear, truncate and pop keep the buffer. Use shrink_to_fit after a big vector becomes small and long-lived. It may reallocate, so do not call it in a hot loop.
  • clone() does not copy capacity; the clone is sized to the length (not guaranteed, but typical).
  • Moving a Vec is cheap (three words) regardless of capacity; the buffer stays where it is.
  • Memory use is roughly capacity * size_of::<T>() plus the 24-byte header on a 64-bit target.