Collections and Iterators
Standard collections and the Iterator pipeline. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Busca en todas las páginas de la documentación
Standard collections and the Iterator pipeline. Results appear in the same fence: same-line // comments when short, multiline // blocks below the sample when not.
Grow vectors and build via collect.
let mut v = vec![1, 2];
v.push(3);
v // [1, 2, 3]Insert-or-update with the entry API.
use std::collections::HashMap;
let mut m = HashMap::new();
*m.entry("a").or_insert(0) += 1;
m["a"] // 1Lazy adapters until collect/consume.
let v: Vec<_> = (1..=5).filter(|n| n % 2 == 0).map(|n| n * 10).collect();
v // [20, 40]Stop at first Err when collecting Results.
let ok: Result<Vec<_>, _> = ["1", "2"].iter().map(|s| s.parse::<i32>()).collect();
ok.unwrap() // [1, 2]Keys stay ordered.
use std::collections::BTreeMap;
let mut m = BTreeMap::new();
m.insert(2, "b");
m.insert(1, "a");
m.keys().copied().collect::<Vec<_>>() // [1, 2]Deduplicate membership tests.
use std::collections::HashSet;
let mut s = HashSet::from([1, 2, 2]);
s.insert(3);
s.len() // 3Fast push/pop at both ends.
use std::collections::VecDeque;
let mut q = VecDeque::from([1, 2]);
q.push_front(0);
q.pop_back() // Some(2)Index pairs and lockstep iteration.
let v: Vec<_> = ["a", "b"].iter().enumerate().map(|(i, s)| (i, *s)).collect();
v // [(0, "a"), (1, "b")]Accumulate a single value.
(1..=4).fold(0, |a, b| a + b) // 10Short-circuit predicates.
[1, 2, 3].iter().any(|n| *n == 2) // true
[1, 2, 3].iter().all(|n| *n > 0) // trueConcatenate and flatten nested iters.
let v: Vec<_> = [[1, 2], [3]].into_iter().flatten().collect();
v // [1, 2, 3]Slice views into windows.
let a = [1, 2, 3, 4];
a.chunks(2).map(|c| c.len()).collect::<Vec<_>>() // [2, 2]Priority queue (max-heap).
use std::collections::BinaryHeap;
let mut h = BinaryHeap::from([1, 5, 3]);
h.pop() // Some(5)Drop elements matching a predicate.
let mut v = vec![1, 2, 3, 4];
v.retain(|n| n % 2 == 0);
v // [2, 4]Sort with a key function.
let mut v = vec!["bb", "a", "ccc"];
v.sort_by_key(|s| s.len());
v // ["a", "bb", "ccc"]Stack versions: Rust 1.97.0 · edition 2024 · Tokio 1.x · serde 1.0
Revisado por Chris St. John·Última actualización: 18 jul 2026