Sub topic 14
Building a Vec or HashMap with collect
This chapter assumes you know basic iterator adapters such as map and filter, and that you can read Option and Result values. You should also have a working Vec and HashMap.
What collect does
Iterator adapters are lazy. Nothing runs until something consumes the iterator. collect is a consumer that gathers every item into a new collection. It works with any type that implements the FromIterator trait, including Vec, HashMap, String and Result.
collect cannot guess which collection you want, so you must name the target type.
Collecting into a Vec
Give the variable a type, or use the turbofish ::<> on the call.
fn main() {
let squares: Vec<u32> = (1..=4).map(|n| n * n).collect();
println!("{:?}", squares); // [1, 4, 9, 16]
let evens = (1..=10).filter(|n| n % 2 == 0).collect::<Vec<u32>>();
println!("{:?}", evens); // [2, 4, 6, 8, 10]
}You can write Vec<_> and let the compiler infer the element type. Without any Vec hint, you get the error "type annotations needed".
Collecting into a HashMap
A HashMap<K, V> is built from an iterator of (K, V) tuples. The zip adapter is a quick way to make such pairs.
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)
}into_iter consumes names, so the strings move into the map. If you only need to borrow them, use iter() and the map will hold references.
If two pairs share a key, the later pair replaces the earlier one.
use std::collections::HashMap;
fn main() {
let pairs = vec![("a", 1), ("a", 2)];
let m: HashMap<_, _> = pairs.into_iter().collect();
println!("{} {}", m.len(), m["a"]); // 1 2
}Collecting a Result
If each item is a Result, you can collect into Result<Vec<T>, E>. You get Ok with every value, or the first Err, and iteration stops there. Option works the same way.
fn main() {
let good: Result<Vec<i32>, _> = "1 2 3".split(' ').map(|s| s.parse::<i32>()).collect();
let bad: Result<Vec<i32>, _> = "1 x 3".split(' ').map(|s| s.parse::<i32>()).collect();
println!("{:?}", good); // Ok([1, 2, 3])
println!("{:?}", bad); // Err(ParseIntError { kind: InvalidDigit })
}Common errors
| Symptom | Cause | Fix |
|---|---|---|
| type annotations needed | No target type for `collect` | Annotate the variable or use `collect::<Vec<_>>()` |
| a value of type `HashMap` cannot be built from an iterator over `i32` | Items are not `(K, V)` tuples | Map each item to a pair first |
| Map has fewer entries than expected | Duplicate keys overwrote each other | Use the entry API to combine values |
| Output order changes between runs | `HashMap` iteration order is unspecified | Collect into a `Vec` and sort |
Exercise
Write a line that turns the Vec<&str> named words into a HashMap<&str, usize> mapping each word to its length.
Show answer
let lengths: HashMap<&str, usize> = words.iter().map(|w| (*w, w.len())).collect();
Exercise
What does collecting an iterator of Result<i32, ParseIntError> into Result<Vec<i32>, ParseIntError> return if the second of three items fails to parse?
Show answer
It returns Err holding the error from the second item. Iteration stops there, so the third item is never examined and no partial Vec is returned.