Collections Basics
8 examples - 5 basic, 3 intermediate - for picking std collections.
Busca en todas las páginas de la documentación
8 examples - 5 basic, 3 intermediate - for picking std collections.
Vec - Default Sequencelet mut v = vec![1, 2, 3];
v.push(4);Growable heap array. Default for lists.
HashMap - Fast Key Lookupuse std::collections::HashMap;
let mut m = HashMap::new();
m.insert("port", 8080);Average O(1) lookup. Unordered keys.
BTreeMap - Sorted Keysuse std::collections::BTreeMap;
let mut m = BTreeMap::new();
m.insert(3, "c");
m.insert(1, "a");Ordered iteration. O(log n) ops.
HashSet / BTreeSetuse std::collections::HashSet;
let s: HashSet<_> = [1, 2, 2].into_iter().collect();Unique elements. 2 deduped.
| Need | Pick |
|---|---|
| Stack-like growth | Vec |
| Fast lookup, no order | HashMap |
| Range scans / order | BTreeMap |
| Unique membership | HashSet |
VecDeque for Queuesuse std::collections::VecDeque;
let mut q = VecDeque::from([1, 2]);
q.push_front(0);Efficient push/pop both ends.
BinaryHeap for Priorityuse std::collections::BinaryHeap;
let mut h = BinaryHeap::from([3, 1, 2]);
assert_eq!(h.pop(), Some(3));Max-heap by default.
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+.
Revisado por Chris St. John·Última actualización: 16 jul 2026