Standard Collections
Collection Iteration
All standard library collections follow a uniform convention for creating iterators: .iter() borrows elements immutably, .iter_mut() (where supported) borrows elements mutably, and .into_iter() consumes the collection to yield owned elements.
Iterator Methods Across All Standard Collections
| Collection | .iter() Yields |
.iter_mut() Yields |
.into_iter() Yields |
Iteration Order |
|---|---|---|---|---|
Vec<T> / VecDeque<T> / LinkedList<T> |
&T |
&mut T |
T |
Front to back (0..len) |
HashMap<K, V> |
(&K, &V) |
(&K, &mut V) |
(K, V) |
Arbitrary |
BTreeMap<K, V> |
(&K, &V) |
(&K, &mut V) |
(K, V) |
Ascending by K: Ord |
HashSet<T> |
&T |
(Not supported) | T |
Arbitrary |
BTreeSet<T> |
&T |
(Not supported) | T |
Ascending by T: Ord |
BinaryHeap<T> |
&T |
(Not supported) | T |
Arbitrary heap-array order |
Specialized Map Iterators (keys, values, values_mut, into_keys, into_values)
In addition to .iter(), .iter_mut(), and .into_iter(), both HashMap<K, V> and BTreeMap<K, V> provide dedicated iterators when you only need keys or values:
| Map Method | Receiver | Item Type |
|---|---|---|
map.keys() |
&self |
&K |
map.values() |
&self |
&V |
map.values_mut() |
&mut self |
&mut V |
map.into_keys() |
self (consumes map) |
K |
map.into_values() |
self (consumes map) |
V |
use std::collections::BTreeMap;
fn main() {
let mut inventory = BTreeMap::from([
(String::from("cpu"), 4_u32),
(String::from("gpu"), 2),
(String::from("ram"), 8),
]);
// 1. Mutate values in place using `values_mut()`:
for count in inventory.values_mut() {
*count *= 10;
}
// 2. Borrow keys and values in sorted key order:
for (item, count) in &inventory {
println!("{item}: {count}");
}
// 3. Consume the map to extract owned `String` keys without cloning:
let part_names: Vec<String> = inventory.into_keys().collect();
println!("Owned part names: {part_names:?}");
}
cpu: 40
gpu: 20
ram: 80
Owned part names: ["cpu", "gpu", "ram"]
Consuming Elements While Keeping the Container (drain)
Vec<T>, VecDeque<T>, String, HashMap<K, V>, HashSet<T>, and BinaryHeap<T> provide a .drain(...) method that moves elements out by value (T or (K, V)) while keeping the collection's allocated heap buffer intact for reuse.