🦀 Rust Beginner

What is Vec<T> in Rust?

Answer

Vec<T> is Rust's dynamically-sized, heap-allocated contiguous array — the most commonly used collection. Create one with vec![1, 2, 3] or Vec::new(). Push elements with v.push(4), access by index with v[0] (panics on out-of-bounds) or v.get(0) (returns Option). The Vec owns its elements — when the Vec is dropped, all elements are dropped. Internally it manages a heap-allocated buffer, doubling capacity when it grows beyond the current capacity. Pre-allocate with Vec::with_capacity(n) to avoid reallocations when you know the approximate size upfront. Iterate over a Vec with a for loop or iterator methods — borrowing it with &v or consuming it.