`Vec`
Vec<T> is a growable, contiguous array on the heap. It is the default list type in Rust: indexed in O(1), appended in amortised O(1), and iterated in a tight pointer loop.
Detailed Explanation
A Vec<T> is three words: a pointer to a heap buffer, a length, and a capacity. Length is how many Ts are live. Capacity is how many would fit before the next allocation. push writes into the spare capacity, or allocates a larger buffer (typically doubling), moves the old elements, and then writes. That doubling is why a series of pushes is amortised O(1) even though a single push can be O(n).
Vec is owned. It drops every element and frees the buffer when it goes out of scope. Cloning a Vec clones every element and allocates a second buffer. Copying a Vec is not possible; it does not implement Copy. Passing vec to a function that takes Vec<T> moves it. Passing &vec or vec.as_slice() borrows the contents.
Indexing is v[i] and panics if i >= v.len(). v.get(i) returns Option<&T>. Prefer get at a boundary that can fail; prefer indexing when you already know the index is in range (for example after enumerate). Slicing v[a..b] also panics on a bad range; v.get(a..b) does not.
Reserve when you know the size: Vec::with_capacity(n) or v.reserve(n) avoids repeated copies during a fill. collect::<Vec<_>>() from an ExactSizeIterator usually reserves once. shrink_to_fit returns unused capacity to the allocator and is rarely worth it in a hot path.
Vec is not a linked list and not a Java ArrayList with synchronized methods. It is not thread-safe by itself. Share it with Mutex<Vec<T>> or do not share it. It is not a C++ std::vector of bool specialisation; Vec<bool> is a normal vector of bytes-as-bools, one byte per element.
When you reach for Vec: almost every list. When you reach for an array: the length is a compile-time constant. When you reach for VecDeque: you pop from the front as often as the back. When you reach for LinkedList: almost never.
Code Examples
fn main() {
let mut ports = Vec::with_capacity(4);
ports.push(8080);
ports.push(8081);
println!("{} {}", ports[0], ports.len()); // prints: 8080 2
println!("{:?}", ports.get(9)); // prints: None
let only_high: Vec<u16> = ports.iter().copied().filter(|p| *p > 8080).collect();
println!("{only_high:?}"); // prints: [8081]
}Common Gotchas
`v[i]` panics on a bad index
Use `get` when the index comes from outside. A panic here is a crash, not an `Err`.
`push` inside a loop without `reserve` copies the buffer repeatedly
Amortised O(1) still means occasional O(n) pauses. `with_capacity` removes them when you know `n`.
A borrow of an element forbids `push`
Resizing may move the buffer. The borrow checker rejects `let x = &v[0]; v.push(1);`. Copy the element first.
`Vec<T>` is `Send`/`Sync` when `T` is
The vector does not add thread safety. Two threads pushing without a lock is a data race and will not compile.