Sub topic 14
Building a Vec or HashMap with collect
This chapter assumes you can read basic iterator chains (iter, map, filter), understand Option and Result, and know how Vec and HashMap store data. It covers how collect decides what to build, how to build the common collections, and which errors you will meet.
What collect does
collect is an iterator method that consumes the iterator and builds a collection from the items. Its signature is generic over the result:
fn collect<B: FromIterator<Self::Item>>(self) -> Bcollect does not know what you want. The compiler picks B from your type annotation, and B must implement the FromIterator trait for the item type the iterator yields. Vec<T> implements FromIterator<T>. HashMap<K, V> implements FromIterator<(K, V)>, so it needs an iterator of two-element tuples.
Choosing the target type
There are three ways to tell the compiler the target. Each one works for any collection.
fn main() {
// 1. Annotate the variable.
let squares: Vec<u32> = (1..=4).map(|n| n * n).collect();
// 2. Use the turbofish on collect.
let evens = (1..=10).filter(|n| n % 2 == 0).collect::<Vec<i32>>();
// 3. Let a function's return type decide.
fn lengths(words: &[&str]) -> Vec<usize> {
words.iter().map(|w| w.len()).collect()
}
println!("{:?}", squares); // [1, 4, 9, 16]
println!("{:?}", evens); // [2, 4, 6, 8, 10]
println!("{:?}", lengths(&["a", "bcd"])); // [1, 3]
}You can write Vec<_> and let the compiler infer the element type. The container must still be named, because collect cannot guess whether you want a Vec, a HashSet, or something else. Omitting it gives the error type annotations needed.
Building a HashMap
To build a HashMap, produce (key, value) tuples. zip is a common way to pair two sequences:
use std::collections::HashMap;
fn main() {
let names = vec!["Ana", "Bo", "Cy"];
let ages = vec![30, 25, 41];
let by_name: HashMap<_, _> = names.into_iter().zip(ages).collect();
println!("{:?}", by_name.get("Bo")); // Some(25)
}map can also produce the tuples from a single source:
use std::collections::HashMap;
fn main() {
let words = ["apple", "fig", "banana"];
let lengths: HashMap<&str, usize> = words.iter().map(|w| (*w, w.len())).collect();
println!("{:?}", lengths.get("fig")); // Some(3)
}For a small fixed table, HashMap::from takes an array of pairs and avoids the iterator entirely:
use std::collections::HashMap;
fn main() {
let limits = HashMap::from([("low", 10), ("high", 99)]);
println!("{}", limits["high"]); // 99
}Duplicate keys
A HashMap holds one value per key. When the iterator yields the same key twice, collect inserts each pair in order, so the last one wins and the earlier value is dropped without any warning:
use std::collections::HashMap;
fn main() {
let pairs = vec![("a", 1), ("b", 2), ("a", 3)];
let m: HashMap<_, _> = pairs.into_iter().collect();
println!("{}", m["a"]); // 3
println!("{}", m.len()); // 2
}If you need to keep every value for a key, collect is the wrong tool. Use the entry API from the earlier chapter, for example entry(k).or_default().push(v).
Owned values versus references
The item type of the iterator decides what the collection stores. iter() yields &T, so collecting it gives a Vec<&T> that borrows from the original:
fn main() {
let v = vec![1, 2, 3];
let refs: Vec<&i32> = v.iter().collect(); // borrows v
let copies: Vec<i32> = v.iter().copied().collect(); // owns its values
println!("{:?} {:?}", refs, copies); // [1, 2, 3] [1, 2, 3]
}A mismatch is a frequent error. Annotating Vec<i32> after v.iter().collect() fails with a value of type Vec<i32> cannot be built from an iterator over elements of type &i32. Fix it with copied() for Copy types, cloned() for types that implement Clone, or into_iter() when you no longer need the source.
A Vec<&T> also keeps the source borrowed. As the borrowing chapter showed, you cannot push to the source while those references are alive.
Collecting into other types
FromIterator is implemented for many standard types, so the same call works well beyond Vec and HashMap:
use std::collections::{BTreeMap, HashSet};
fn main() {
let reversed: String = "stressed".chars().rev().collect();
println!("{reversed}"); // desserts
let unique: HashSet<i32> = [3, 1, 3, 2, 1].into_iter().collect();
println!("{}", unique.len()); // 3
let sorted: BTreeMap<&str, i32> = [("pear", 2), ("apple", 5)].into_iter().collect();
println!("{:?}", sorted); // {"apple": 5, "pear": 2}
}BTreeMap iterates in key order, which makes it useful when you need deterministic output from a collect. A HashMap or HashSet iterates in an unspecified order that can change between runs.
Collecting Results and Options
Collecting an iterator of Result<T, E> into Result<Vec<T>, E> is one of the most useful forms. It returns Ok with every value if all items succeed. At the first Err, it stops and returns that error.
use std::num::ParseIntError;
fn parse_all(input: &str) -> Result<Vec<i32>, ParseIntError> {
input.split(',').map(|s| s.trim().parse::<i32>()).collect()
}
fn main() {
println!("{:?}", parse_all("1, 2, 3")); // Ok([1, 2, 3])
println!("{:?}", parse_all("1, x, 3")); // Err(ParseIntError { kind: InvalidDigit })
}The same pattern works with Option: an iterator of Option<T> collects into Option<Vec<T>>, which is None if any item is None. Short-circuiting means later items are not processed once an error appears.
Adding to an existing collection
collect always creates a new collection. To add items to one that already exists, use extend, which accepts any iterator and appends to the Vec or inserts into the HashMap:
use std::collections::HashMap;
fn main() {
let mut v = vec![1, 2];
v.extend((3..=5).map(|n| n * 10));
println!("{:?}", v); // [1, 2, 30, 40, 50]
let mut m = HashMap::from([("a", 1)]);
m.extend([("b", 2), ("a", 9)]);
println!("{} {}", m["a"], m["b"]); // 9 2
}As with collect, a repeated key overwrites the old value.
Common errors
| Symptom | Cause | Fix | Column | Column |
|---|---|---|---|---|
| `type annotations needed` | No target type for `collect` | Annotate the variable or use `collect::<Vec<_>>()` | ||
| `cannot be built from an iterator over elements of type &T` | `iter()` yields references | Add `copied()` or `cloned()`, or use `into_iter()` | ||
| `a value of type HashMap<..> cannot be built from ... of type X` | Items are not `(K, V)` tuples | Add `map(\ | x\ | (key, value))` |
| Map has fewer entries than the input | Duplicate keys overwrote earlier ones | Use the `entry` API to merge values | ||
| Output order changes between runs | `HashMap` order is unspecified | Collect into a `BTreeMap`, or sort a `Vec` of pairs |
Exercise
Write a function fn index(words: &[&str]) -> HashMap<&str, usize> that maps each word to its position in the slice. What happens to a word that appears twice, and why?
Show answer
Use words.iter().enumerate().map(|(i, w)| (*w, i)).collect(). The enumerate call yields (usize, &&str) pairs, and the closure swaps them into (&str, usize) tuples with *w. A repeated word ends up with the index of its last occurrence, because collect inserts pairs in order and each insert overwrites the previous value for that key.
Exercise
A function receives Vec<&str> such as ["4", "8", "x"] and must return the parsed numbers, or fail if any entry is invalid. What return type and collect target do you use, and what does the call return for this input?
Show answer
Return Result<Vec<i32>, std::num::ParseIntError> and collect items.iter().map(|s| s.parse::<i32>()) into it. For ["4", "8", "x"] the result is Err with an InvalidDigit error, because collect stops at the first failure and discards the values already parsed.