Vec<T> (Rust)
Vec<T> is Rust's growable, heap-allocated array — an ordered list of values of the same type that can shrink and grow at runtime. It is the most common collection in Rust.
Rust
A Vec owns its elements on the heap and resizes automatically as you push and pop. Create one with vec![1, 2, 3] or Vec::new(). Index with v[i] (panics if out of bounds) or v.get(i) (returns an Option, safe).
Vectors are iterable, so they work directly with for loops and iterator adapters like .iter().map().filter().collect(). Because a Vec owns its data, moving it transfers all the elements; borrow it (&v or &mut v) to share without moving.
Use a Vec when you need an ordered, dynamically sized sequence. For a fixed compile-time size use an array [T; N]; for borrowed views of a contiguous range use a slice &[T].
Syntax
let mut v: Vec<i32> = vec![1, 2, 3];
v.push(4);Examples
Rust
fn main() {
let mut nums = vec![1, 2, 3];
nums.push(4);
let sum: i32 = nums.iter().sum();
println!("{:?} sum={}", nums, sum);
}Output:
[1, 2, 3, 4] sum=10