Collections Basics
8 examples - 5 basic, 3 intermediate - for picking std collections.
Prerequisites
Basic Examples
1. Vec - Default Sequence
let mut v = vec![1, 2, 3];
v.push(4);Growable heap array. Default for lists.
2. HashMap - Fast Key Lookup
use std::collections::HashMap;
let mut m = HashMap::new();
m.insert("port", 8080);Average O(1) lookup. Unordered keys.
3. BTreeMap - Sorted Keys
use std::collections::BTreeMap;
let mut m = BTreeMap::new();
m.insert(3, "c");
m.insert(1, "a");Ordered iteration. O(log n) ops.
4. HashSet / BTreeSet
use std::collections::HashSet;
let s: HashSet<_> = [1, 2, 2].into_iter().collect();Unique elements. 2 deduped.
5. When to Pick Which
| Need | Pick |
|---|---|
| Stack-like growth | Vec |
| Fast lookup, no order | HashMap |
| Range scans / order | BTreeMap |
| Unique membership | HashSet |
Intermediate Examples
6. VecDeque for Queues
use std::collections::VecDeque;
let mut q = VecDeque::from([1, 2]);
q.push_front(0);Efficient push/pop both ends.
7. BinaryHeap for Priority
use std::collections::BinaryHeap;
let mut h = BinaryHeap::from([3, 1, 2]);
assert_eq!(h.pop(), Some(3));Max-heap by default.
8. Capacity Hints
let mut v = Vec::with_capacity(1000);Reduce reallocations when size known.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.