Skip to content

Collections & Iterators

Rust ships with a powerful set of standard-library collections and a lazy, zero-cost iterator system. Together they let you store, transform, and consume data without manual loops or unnecessary allocations.

This module walks through five focused lessons:

LessonTopic
Vec<T> & StringGrowable sequences and owned text
HashMap<K, V>Key-value lookup with the entry API
IteratorsLazy chains: map, filter, collect, fold
ClosuresCapturing environments; Fn / FnMut / FnOnce

Rust’s most-used collections and when to reach for each:

  • Vec<T> — ordered, contiguous heap array. Use when you need indexed access or a growable list.
  • String — owned, UTF-8 text. Use when you need to build or mutate text at runtime.
  • HashMap<K, V> — hash table mapping keys to values. Use for fast lookup by key.
  • HashSet<T> — set of unique values. Use when membership testing is all you need.

Every Rust collection exposes an iterator. Iterators are lazy — no work happens until a consumer (like collect, sum, or for) pulls values through the chain.

let v = vec![1, 2, 3, 4, 5];
// Nothing executes yet — adaptor chain is just a description
let chain = v.iter().filter(|&&x| x % 2 == 0).map(|&x| x * 10);
// Consumer drives the chain
let result: Vec<i32> = chain.collect();
use std::collections::HashMap;
use std::collections::HashSet;
fn main() {
// Vec<i32>
let mut v: Vec<i32> = vec![1, 2, 3];
v.push(4);
println!("Vec: {:?}", v);
// String
let mut s = String::from("Hello");
s.push_str(", Rust!");
println!("String: {}", s);
// HashMap<&str, i32> — sort keys for deterministic output
let mut map = HashMap::new();
map.insert("one", 1);
map.insert("two", 2);
map.insert("three", 3);
let mut keys: Vec<&str> = map.keys().cloned().collect();
keys.sort();
for k in &keys {
println!("{}: {}", k, map[k]);
}
// HashSet<i32>
let set: HashSet<i32> = vec![1, 2, 3, 2, 1].into_iter().collect();
let mut items: Vec<i32> = set.into_iter().collect();
items.sort();
println!("Set: {:?}", items);
}
Which collection would you choose for fast lookup by a String key?
When does an iterator adaptor (like map or filter) actually execute its work?
What is the idiomatic way to iterate a HashMap and get deterministic output order?