Skip to content
ImagineWorld

Collections and Iterators

node_idnode-book_oop-to-rust_chapter-09-collections-and-iterators
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num9
chapter_titleCollections and Iterators
governed_byCORPUS
constitutional_citationCONSTITUTION
local graph

Multum in parvo. (Much in little.)

Every program of substance works with collections of data. Customer records, configuration entries, parsed tokens, network packets: the ability to store, retrieve, and process groups of values is fundamental. Object-oriented languages provide collection libraries (Java’s Collections Framework, C#‘s System.Collections, C++‘s STL) that offer similar abstractions: lists, maps, sets, and queues with various implementation trade-offs. Rust’s standard library provides equivalent collections, but the ownership system changes how they are used. Collections own their elements. Iteration borrows or consumes. Understanding these interactions is essential for working effectively with Rust’s collection types.

This chapter explores Rust’s primary collections and the iterator system that unifies operations across them. The patterns established here appear throughout Rust code, from simple scripts to complex systems.

Vec: the workhorse collection

Vec is Rust’s growable array, equivalent to Java’s ArrayList, C#‘s List, or C++‘s std::vector. It stores elements contiguously in heap-allocated memory, providing O(1) indexed access and amortized O(1) append. For most use cases requiring a sequence of values, Vec is the default choice.

Creating a Vec uses either the constructor or the vec! macro:

let mut numbers: Vec<i32> = Vec::new();
numbers.push(1);
numbers.push(2);
let words = vec!["hello", "world"];

The vec! macro is syntactic sugar that creates a Vec and populates it with the provided elements. It is the idiomatic way to create vectors with initial contents.

When a Vec is dropped, it drops every element it contains. When you push a value into a Vec, ownership transfers to the vector. When you remove a value, ownership transfers back to you. This ownership model means Vec owns the strings it contains, not just pointers to strings owned elsewhere.

Capacity and reallocation

A Vec maintains both a length (how many elements it contains) and a capacity (how many elements it can hold before needing to reallocate). When you push an element and the length equals the capacity, the Vec allocates a larger buffer (typically doubling the capacity), copies existing elements to the new buffer, and deallocates the old one. This reallocation is why push has amortized O(1) complexity: most pushes are constant time, but occasional pushes trigger expensive reallocations.

Understanding capacity matters for performance-sensitive code. If you know approximately how many elements a Vec will hold, pre-allocating avoids reallocations during population:

let mut results = Vec::with_capacity(1000);
for i in 0..1000 {
results.push(compute(i)); // No reallocations
}

The with_capacity method creates a Vec that can hold at least the specified number of elements without reallocating. The actual capacity might be higher due to allocator behavior, but you are guaranteed at least what you requested.

For cases where you are collecting from an iterator with a known size, the iterator’s size hint enables automatic capacity optimization. The collect method uses this hint to pre-allocate appropriately.

Slices as views into collections

A slice is a view into a contiguous sequence of elements. Where Vec is an owned, growable collection, &[T] is a borrowed, fixed-size view. Slices do not own their data; they borrow it from some underlying storage, whether that is a Vec, an array, or another slice.

The relationship between Vec and slices mirrors the relationship between String and &str. A Vec can be borrowed as a slice, and functions that need only to read elements typically accept slices rather than vectors:

fn sum(numbers: &[i32]) -> i32 {
numbers.iter().sum()
}
let vec = vec![1, 2, 3, 4, 5];
let total = sum(&vec); // Vec coerces to slice
let array = [10, 20, 30];
let total = sum(&array); // Arrays also coerce to slices

By accepting &[T] rather than &Vec<T>, the function works with any contiguous sequence: vectors, arrays, or slices of slices. This flexibility follows from Deref coercion (covered in Chapter 6) and is the idiomatic way to write functions that read from sequences.

Slices support indexing, iteration, and various methods for searching and manipulating views. The split, chunks, and windows methods produce iterators over sub-slices, enabling efficient processing of data in pieces without copying.

Mutable slices (&mut [T]) allow modifying elements in place. A function accepting &mut [T] can modify the slice’s contents but cannot change its length. Growing or shrinking requires ownership, which only the original Vec provides.

String vs &str

Text handling in Rust distinguishes between owned strings (String) and borrowed string slices (&str). This distinction confuses developers from languages where strings are typically a single type with reference semantics. Understanding the difference is essential because strings appear constantly, and using the wrong type creates friction with APIs and the borrow checker.

Owned vs borrowed strings

String is an owned, growable, heap-allocated UTF-8 string. It is analogous to Vec<u8> with the guarantee that the bytes form valid UTF-8. When you need to build a string, modify a string, or store a string that outlives the current scope, you use String.

&str is a borrowed view into UTF-8 data. It might view a String’s contents, a string literal embedded in the binary, or a slice of some other UTF-8 source. Like all borrows, &str cannot outlive the data it references. String literals have the special type &‘static str, meaning they live for the entire program (they are embedded in the executable).

The distinction reflects ownership. String literals are baked into the binary and never deallocated; borrowing them as &‘static str is always safe. Runtime strings require allocation and deallocation; String manages this lifecycle. When a function needs to read a string without taking ownership, it accepts &str. When it needs to own the string, it accepts String or impl Into<String>.

fn greet(name: &str) {
println!("Hello, {}!", name);
}
greet("world"); // &'static str
greet(&String::from("Rust")); // &String coerces to &str

The function accepts &str, allowing callers to pass string literals, borrowed Strings, or any other string slice. This is the idiomatic pattern for functions that read strings.

String building strategies

Building strings efficiently requires understanding that String, like Vec, reallocates when it grows beyond its capacity. For simple cases, the format! macro or + operator suffice:

let greeting = format!("Hello, {}!", name);
let full = first_name + " " + &last_name;

The + operator consumes the left operand and appends the right, potentially reusing the left string’s buffer if it has sufficient capacity. This makes chained concatenation (a + b + c) efficient but requires ownership of the leftmost string.

For building strings incrementally, particularly in loops, String’s push and push_str methods avoid the overhead of repeated formatting:

let mut result = String::with_capacity(estimated_length);
for item in items {
result.push_str(&item.to_string());
result.push('\n');
}

Pre-allocating capacity when the final size is approximately known prevents reallocations during building. For joining many strings with a separator, the iterator method join is cleaner and often more efficient:

let lines: Vec<&str> = vec!["first", "second", "third"];
let combined = lines.join("\n");

The standard library also provides std::fmt::Write for writing formatted data into strings, useful when building complex output with multiple format operations.

UTF-8, bytes, and the meaning of length

Rust strings are UTF-8 encoded, and this choice permeates the string API in ways that surprise developers from languages with different string models. The len() method returns the number of bytes, not the number of characters. For ASCII text, these coincide. For text with non- ASCII characters, they diverge significantly.

let ascii = "hello";
let cyrillic = "привет"; // Russian "hello"
let emoji = "👋🌍";
println!("{}", ascii.len()); // 5 bytes
println!("{}", cyrillic.len()); // 12 bytes (2 bytes per Cyrillic letter)
println!("{}", emoji.len()); // 8 bytes (4 bytes per emoji)

This design reflects a deliberate philosophy. UTF-8 is a variable-width encoding where characters occupy one to four bytes. Counting “characters” requires iterating through the entire string, an O(n) operation. Returning the byte length is O(1) and unambiguous. Rust makes the cheap operation obvious and requires explicit work for the expensive one.

The concept of “character” itself is fraught with ambiguity. Unicode defines code points, but a single perceived character might consist of multiple code points. The letter “é” can be represented as a single code point (U+00E9, “Latin Small Letter E with Acute”) or as two code points (U+0065 “Latin Small Letter E” followed by U+0301 “Combining Acute Accent”). Both render identically, but they have different lengths in code points.

The chars() method iterates over Unicode scalar values (code points), which is closer to what developers often mean by “characters” but still not quite right for all use cases:

let word = "café";
println!("{}", word.len()); // 5 bytes (é is 2 bytes)
println!("{}", word.chars().count()); // 4 code points

For text processing that must handle human-perceived characters correctly, the relevant unit is the grapheme cluster: a base character plus any combining marks that modify it. The string “é” (composed form) and “é” (decomposed form with combining accent) should both count as one grapheme cluster. Emoji with skin tone modifiers, flags composed of regional indicators, and many other cases require grapheme-aware processing.

The standard library does not provide grapheme cluster iteration because the Unicode rules are complex and evolve over time. The unicode-segmentation crate provides this functionality:

use unicode_segmentation::UnicodeSegmentation;
let text = "é"; // e + combining acute + combining acute (contrived example)
println!("{}", text.graphemes(true).count()); // 1 grapheme cluster

This layered approach reflects Rust’s philosophy of keeping the standard library lean while enabling correct behavior through well-maintained crates. The standard library provides fast, unambiguous byte-level operations. Code point iteration is available for cases where that abstraction is appropriate. Grapheme cluster handling lives in a dedicated crate that tracks Unicode specification updates.

String indexing follows from these design choices. Rust does not allow indexing strings by integer because the result would be ambiguous (byte? code point? grapheme?) and potentially O(n) for code points or graphemes. Instead, you slice by byte ranges, and the slice operation panics if the range does not fall on code point boundaries:

let hello = "Hello, 世界";
let slice = &hello[0..5]; // "Hello" - valid, ASCII bytes
// let bad = &hello[0..8]; // Panics: byte 8 is mid-character
let world = &hello[7..]; // "世界" - valid, starts at character boundary

For safe slicing without panics, use get () which returns Option:

if let Some(slice) = hello.get(0..8) {
println!("{}", slice);
} else {
println!("Invalid byte range");
}

This strictness prevents subtle bugs. In languages that allow arbitrary indexing into UTF-8 strings, slicing at the wrong position produces garbage or crashes. Rust makes the developer acknowledge string encoding explicitly, leading to code that either handles Unicode correctly or fails clearly during development rather than corrupting data in production.

When working with strings that are known to be ASCII, the as_bytes() method provides a byte slice that can be indexed freely. For performance-critical ASCII processing, working with bytes avoids the overhead of UTF-8 validation:

let ascii = "HELLO";
let bytes = ascii.as_bytes();
println!("{}", bytes[0] as char); // 'H'

The is_ascii() method checks whether a string contains only ASCII characters, useful for validating before byte-level processing.

Understanding these layers (bytes, code points, grapheme clusters) and choosing the appropriate abstraction for each task is essential for correct string handling in Rust. The language does not hide the complexity; it exposes it through a deliberate API that guides developers toward correct choices.

Maps associate keys with values, providing efficient lookup by key. Rust provides two primary map types: HashMap for hash-based O(1) average lookup and BTreeMap for ordered keys with O(log n) lookup.

HashMap uses hashing to distribute keys across buckets, providing fast average-case performance. Keys must implement Hash and Eq. Most primitive types and String implement these traits; custom types can derive them:

use std::collections::HashMap;
let mut scores: HashMap<String, i32> = HashMap::new();
scores.insert(String::from("Alice"), 100);
scores.insert(String::from("Bob"), 85);
if let Some(score) = scores.get("Alice") {
println!("Alice scored {}", score);
}

BTreeMap stores keys in sorted order using a B-tree structure. Keys must implement Ord. Use BTreeMap when you need ordered iteration, range queries, or deterministic iteration order:

use std::collections::BTreeMap;
let mut events: BTreeMap<u64, String> = BTreeMap::new();
events.insert(1000, String::from("Start"));
events.insert(2000, String::from("Middle"));
events.insert(3000, String::from("End"));
// Iterate in key order
for (timestamp, event) in &events {
println!("{}: {}", timestamp, event);
}

The choice between HashMap and BTreeMap depends on requirements. HashMap is faster for pure lookup workloads. BTreeMap provides ordering guarantees and efficient range queries. When iteration order does not matter and keys are hashable, HashMap is the default choice.

Entry API for efficient updates

A common pattern with maps is updating a value if it exists or inserting a default if it does not. The naive approach requires two lookups:

// Inefficient: looks up key twice
if !map.contains_key(&key) {
map.insert(key.clone(), default_value);
}
let value = map.get_mut(&key).unwrap();

The Entry API provides a single lookup that returns an entry representing either an occupied slot or a vacant slot. You can then operate on the entry without additional lookups:

use std::collections::HashMap;
let mut word_counts: HashMap<String, u32> = HashMap::new();
for word in text.split_whitespace() {
*word_counts.entry(word.to_string()).or_insert(0) += 1;
}

The entry method returns an Entry enum. The or_insert method inserts the provided value if the entry is vacant and returns a mutable reference to the value (new or existing). This pattern is both more efficient and more readable than the contains/insert/get sequence.

The Entry API provides several insertion strategies: or_insert for a default value, or_insert_with for a lazily computed default, or_default for types implementing Default, and and_modify for updating existing values before potentially inserting. These methods chain naturally:

map.entry(key)
.and_modify(|v| *v += 1)
.or_insert(1);

This pattern increments the value if the key exists or inserts 1 if it does not, all in a single lookup.

HashSet and BTreeSet

Sets store unique values without associated data. HashSet provides O(1) average membership testing; BTreeSet provides O(log n) with ordered iteration. Their APIs mirror the map types without the value component.

use std::collections::HashSet;
let mut seen: HashSet<i32> = HashSet::new();
seen.insert(1);
seen.insert(2);
seen.insert(1); // No effect; 1 is already present
println!("Contains 1: {}", seen.contains(&1)); // true
println!("Size: {}", seen.len()); // 2

Sets support standard set operations: union, intersection, difference, and symmetric difference. These operations return iterators rather than new sets, allowing lazy evaluation and chaining:

let a: HashSet<_> = [1, 2, 3].into_iter().collect();
let b: HashSet<_> = [2, 3, 4].into_iter().collect();
let union: HashSet<_> = a.union(&b).cloned().collect();
let intersection: HashSet<_> = a.intersection(&b).cloned().collect();

Use sets when you need to track membership, eliminate duplicates, or perform set operations. The choice between HashSet and BTreeSet follows the same reasoning as maps: HashSet for speed when order does not matter, BTreeSet when you need sorted iteration or range queries.

Other collections: VecDeque, BinaryHeap

The standard library provides additional collections for specific use cases.

VecDeque is a double-ended queue implemented as a ring buffer. It provides O(1) insertion and removal at both ends, making it suitable for queues, work-stealing deques, or any scenario requiring efficient operations at both ends:

use std::collections::VecDeque;
let mut queue: VecDeque<String> = VecDeque::new();
queue.push_back(String::from("first"));
queue.push_back(String::from("second"));
while let Some(item) = queue.pop_front() {
println!("Processing: {}", item);
}

Unlike Vec, which has O(n) insertion at the front (due to shifting elements), VecDeque handles front operations efficiently. The trade-off is slightly higher constant factors for indexed access due to the ring buffer arithmetic.

BinaryHeap is a priority queue implemented as a max-heap. It provides O(log n) insertion and O(log n) removal of the maximum element, with O(1) access to the maximum:

use std::collections::BinaryHeap;
let mut tasks = BinaryHeap::new();
tasks.push(3); // priority 3
tasks.push(1); // priority 1
tasks.push(4); // priority 4
while let Some(priority) = tasks.pop() {
println!("Processing priority {}", priority); // 4, 3, 1
}

For a min-heap, wrap values in std::cmp::Reverse or implement a newtype with reversed Ord. BinaryHeap is useful for scheduling, graph algorithms like Dijkstra’s shortest path, or any scenario requiring processing in priority order.

The Iterator trait

Iterators are the unifying abstraction for processing sequences in Rust. The Iterator trait defines a single required method, next, which returns Option<Self::Item>: Some(value) for each element, None when exhausted. This simple interface enables a rich ecosystem of adapters and consumers that work with any iterator.

trait Iterator {
type Item;
fn next(&mut self) -> Option<Self::Item>;
// Many provided methods...
}

Collections provide methods that return iterators. By convention, iter() returns an iterator over references (&T), iter_mut() returns an iterator over mutable references (&mut T), and into_iter() returns an iterator that takes ownership (T). This naming convention appears consistently across the standard library.

Iterator adapters

Adapters transform iterators into new iterators without consuming elements immediately. They are lazy: calling map does not process any elements, it produces a new iterator that will transform elements when consumed. This laziness enables zero-cost abstraction; the compiler often optimizes iterator chains into loops as efficient as hand-written code.

The most common adapters include:

map transforms each element through a closure:

let doubled: Vec<_> = numbers.iter().map(|x| x * 2).collect();

filter retains elements matching a predicate:

let evens: Vec<_> = numbers.iter().filter(|x| *x % 2 == 0).collect();

flat_map maps and flattens, useful for one-to-many transformations:

let all_chars: Vec<_> = words.iter().flat_map(|w| w.chars()).collect();

take and skip limit iteration:

let first_five: Vec<_> = numbers.iter().take(5).collect();
let rest: Vec<_> = numbers.iter().skip(5).collect();

enumerate pairs elements with their indices:

for (index, value) in numbers.iter().enumerate() {
println!("{}: {}", index, value);
}

Adapters chain to express complex transformations declaratively. A chain like iter().filter(…).map(…).take(…) reads as a pipeline of transformations, each step building on the previous.

Collecting into different types

The collect method consumes an iterator and gathers elements into a collection. The target collection type is inferred from context or specified with turbofish syntax:

let vec: Vec<_> = iter.collect();
let set: HashSet<_> = iter.collect();
let map: HashMap<_, _> = pairs.collect();
let string: String = chars.collect();

The flexibility of collect comes from the FromIterator trait, which any type can implement. Vec, HashSet, HashMap, String, and many others implement FromIterator, making them valid collection targets.

For fallible operations, collect can gather Results into a Result of a collection:

let numbers: Result<Vec<i32>, _> = strings.iter()
.map(|s| s.parse::<i32>())
.collect();

If any parse fails, the entire collect returns Err. If all succeed, it returns Ok with the collected vector. This pattern is invaluable for processing sequences where any element might fail.

IntoIterator and iteration patterns

The IntoIterator trait enables types to be used in for loops. When you write for x in collection, Rust calls collection.into_iter() to obtain an iterator. Types implement IntoIterator to specify what kind of iterator they produce.

Collections typically implement IntoIterator three ways:

  • For &Collection, producing an iterator over &T
  • For &mut Collection, producing an iterator over &mut T
  • For Collection (by value), producing an iterator over T that consumes the collection

This pattern explains why both for x in &vec and for x in vec work but mean different things. The first borrows the vector and iterates over references; the second consumes the vector and iterates over owned values.

Understanding IntoIterator helps when writing generic code. A function accepting impl IntoIterator<Item = T> works with any type that can produce an iterator of T values: vectors, arrays, slices, ranges, or custom types.

Implementing Iterator for custom types

Creating custom iterators requires implementing the Iterator trait, which has one required method: next. The following example implements a Fibonacci sequence iterator:

struct Fibonacci {
current: u64,
next: u64,
limit: Option<u64>,
}
impl Fibonacci {
fn new() -> Self {
Fibonacci {
current: 0,
next: 1,
limit: None,
}
}
fn with_limit(limit: u64) -> Self {
Fibonacci {
current: 0,
next: 1,
limit: Some(limit),
}
}
}
impl Iterator for Fibonacci {
type Item = u64;
fn next(&mut self) -> Option<Self::Item> {
// Check limit if set
if let Some(limit) = self.limit {
if self.current > limit {
return None;
}
}
let result = self.current;
let new_next = self.current.checked_add(self.next)?; // Handle overflow
self.current = self.next;
self.next = new_next;
Some(result)
}
}
fn main() {
// Take first 10 fibonacci numbers
let fibs: Vec<_> = Fibonacci::new().take(10).collect();
println!("First 10: {:?}", fibs);
// Limited fibonacci
let fibs_under_100: Vec<_> = Fibonacci::with_limit(100).collect();
println!("Under 100: {:?}", fibs_under_100);
// Using iterator adapters
let sum_of_even: u64 = Fibonacci::with_limit(1000)
.filter(|n| n % 2 == 0)
.sum();
println!("Sum of even fibs under 1000: {}", sum_of_even);
}

Once Iterator is implemented, all adapter methods (map, filter, take) and consumers (collect, sum, count) work automatically. The custom iterator integrates seamlessly with the standard library’s iterator ecosystem.

fold and reduce patterns

The fold method accumulates a value across the iterator, starting from an initial value. It is the foundation for many reduction operations:

fn main() {
let numbers = vec![1, 2, 3, 4, 5];
// fold: accumulate with initial value
let sum = numbers.iter().fold(0, |acc, &x| acc + x);
let product = numbers.iter().fold(1, |acc, &x| acc * x);
println!("Sum: {}, Product: {}", sum, product);
// fold to build a string
let csv = numbers.iter()
.fold(String::new(), |mut acc, &x| {
if !acc.is_empty() {
acc.push(',');
}
acc.push_str(&x.to_string());
acc
});
println!("CSV: {}", csv);
// reduce: like fold but uses first element as initial
let max = numbers.iter().copied().reduce(|a, b| if a > b { a } else { b });
println!("Max: {:?}", max);
// fold to create a HashMap
use std::collections::HashMap;
let counts: HashMap<char, usize> = "hello world"
.chars()
.fold(HashMap::new(), |mut acc, c| {
*acc.entry(c).or_insert(0) += 1;
acc
});
println!("Char counts: {:?}", counts);
// scan: fold that yields intermediate values
let running_sum: Vec<_> = numbers.iter()
.scan(0, |state, &x| {
*state += x;
Some(*state)
})
.collect();
println!("Running sum: {:?}", running_sum);
}

The fold method expresses a wide variety of aggregations. The closure receives an accumulator and the current element, returning the new accumulator value. For operations where the first element serves as the natural starting value, reduce provides a slightly more concise form.

Rust’s iterators serve the same purpose as Java’s Stream API or C#‘s LINQ: declarative, composable data processing. The concepts map directly: map is map, filter is filter/where, collect resembles terminal operations or ToList/ToArray. Developers familiar with these APIs will find Rust’s iterators natural once the ownership implications are understood.

The key differences stem from ownership. Java streams process references to objects managed by garbage collection; the original collection remains accessible during and after streaming. Rust iterators may borrow (iter), mutably borrow (iter_mut), or consume (into_iter) the source collection. The choice affects what you can do with the collection during iteration and whether it survives afterward.

Java’s parallel streams and C#‘s Parallel LINQ enable automatic parallelization. Rust does not include parallel iterators in the standard library, but the rayon crate provides par_iter() methods that parallelize iterator chains with minimal code changes. The type system ensures that closures passed to parallel iterators are thread-safe (implementing Send and Sync as required), catching data race bugs at compile time that would be runtime errors in other languages.

Another difference is laziness. Java streams are lazy; LINQ is lazy except for methods like ToList that force evaluation. Rust iterators are always lazy until a consuming method (collect, for_each, fold, count, etc.) drives iteration. Intermediate operations like map and filter build up a chain of adapters; nothing executes until consumption. This model ensures that iterator chains have predictable performance characteristics and that short-circuiting operations like take work correctly.

The mental model transfers directly: if you have written Java code like stream.filter(…).map(…).collect(Collectors.toList()), the Rust equivalent is iter.filter(...).map(...).collect::<Vec<_>>(). The syntax differs, but the concepts align. The additional consideration is choosing the right iteration method (iter, iter_mut, into_iter) based on ownership requirements, a decision that does not exist in garbage-collected languages.

Topics Covered

Rust’s collections store owned values, with Vec<T> serving as the primary sequence type and HashMap<K, V> as the primary associative container. Slices (&[T]) provide borrowed views into contiguous data, enabling functions to accept any sequence without requiring ownership. The relationship between Vec and slices parallels String and &str: owned versus borrowed, growable versus fixed-view.

The Entry API enables efficient update-or-insert operations on maps, avoiding redundant lookups. Sets (HashSet, BTreeSet) track unique values with the same hash-versus-ordered trade-offs as maps. Specialized collections like VecDeque and BinaryHeap serve specific algorithmic needs.

Iterators unify sequence processing across all collection types. The Iterator trait’s next method is the foundation; adapter methods like map, filter, and take transform iterators lazily. The collect method consumes iterators into collections, with the target type determined by context or explicit annotation. IntoIterator enables for loop syntax and generic iteration.

Rust’s iterator patterns parallel Java Streams and LINQ but with ownership semantics that affect how collections are accessed during iteration. The choice between iter(), iter_mut(), and into_iter() determines borrowing versus consuming behavior, a distinction that does not exist in garbage-collected languages but provides precise control in Rust.

The next chapter explores modules and crate structure, addressing how Rust organizes code as projects grow beyond single files.