Rust Reference ยท Collections
Rust Vec::new, push and pop
Reference for Vec::new, Vec::with_capacity, push, pop, last, clear and truncate in Rust, with return values, ownership notes and amortized cost.
These are the basic operations on a Vec<T>: create an empty one with Vec::new() (or Vec::with_capacity), add to the end with push, remove from the end with pop. Together they make a vector behave like a stack.
push takes the element by value, so the vector becomes its owner. pop returns Option<T>: Some(value) for the last element, or None when the vector is empty. Neither needs the vector to be pre-sized.
let mut stack = Vec::new(); stack.push(10); let top = stack.pop(); // Some(10)
Try it
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.
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
impl<T> Vec<T> { pub const fn new() -> Vec<T>; pub fn with_capacity(capacity: usize) -> Vec<T>; pub fn push(&mut self, value: T); pub fn pop(&mut self) -> Option<T>; pub fn pop_if(&mut self, predicate: impl FnOnce(&mut T) -> bool) -> Option<T>; pub fn clear(&mut self); pub fn truncate(&mut self, len: usize); }
| Name | Description |
|---|---|
capacity |
How many elements to make room for. The vector starts empty. |
value |
The element to append. It is moved into the vector. |
predicate |
For pop_if, a closure that receives &mut T for the last element and returns whether to remove it. |
len |
For truncate, the new length. Larger than the current length does nothing. |
Returns: push returns nothing. pop and pop_if return Option<T>. Vec::new is const, so it can initialize a static.
Panics: push panics only if the new capacity would overflow isize::MAX bytes. Allocation failure aborts the process.
Usage notes
Vec::new()does not allocate. The firstpushallocates a small buffer, and later pushes double it as needed, so pushing is amortized O(1).- Type inference usually fills in
Tfrom later pushes. When nothing constrains it, writeVec::<i32>::new()or annotate the binding. pushcan move the buffer. After a reallocation, old element addresses change; the borrow checker prevents you from holding references across apush.popremoves from the end only. To take from the front useremove(0)(O(n)) or switch toVecDequewithpop_front.clearandtruncatedrop the removed elements (running their destructors) but keep the allocated capacity.pop_ifis stable since Rust 1.86. It is handy for loops like "remove trailing blanks".- Accessing the end without removing: use
last()orlast_mut()fromfirst, last, split_at.