Sub topic 12
Gathering results with collect
This chapter assumes you know how iterator adapters like map and filter work, that iterators are lazy, and how Option and Result behave. Here you will see how collect turns an iterator into a concrete collection.
What collect does
collect is a consuming method. It drives the iterator to the end and builds a value from the items. The result type is not fixed by collect itself. It is chosen by the type you ask for, and that type must implement the FromIterator trait.
fn main() {
let doubled: Vec<i32> = (1..4).map(|n| n * 2).collect();
println!("{:?}", doubled); // [2, 4, 6]
}Without a target type, the compiler reports "type annotations needed". You can supply the type in three ways:
- Annotate the variable:
let v: Vec<i32> = ... - Use the turbofish on the call:
.collect::<Vec<i32>>() - Let the type come from context, such as a function's return type.
You can write _ for parts the compiler can infer, as in collect::<Vec<_>>().
Collecting into different types
Many standard types implement FromIterator. The same pipeline can end in a different container by changing only the type.
| Target type | Items the iterator must yield |
|---|---|
| `Vec<T>` | `T` |
| `String` | `char`, `&str` or `String` |
| `HashMap<K, V>` | `(K, V)` tuples |
| `HashSet<T>` | `T` |
| `Result<C, E>` | `Result<T, E>`, where `C` is `FromIterator<T>` |
| `Option<C>` | `Option<T>`, where `C` is `FromIterator<T>` |
A HashMap needs pairs. A later pair with an existing key replaces the earlier value.
use std::collections::HashMap;
fn main() {
let names = vec!["ann", "bob", "cy"];
let lens: HashMap<&str, usize> = names.iter().map(|n| (*n, n.len())).collect();
println!("{}", lens["bob"]); // 3
let reversed: String = "hello".chars().rev().collect();
println!("{}", reversed); // olleh
}Collecting Results
Collecting into Result<Vec<_>, _> is the most useful special case. If every item is Ok, you get Ok with the vector. At the first Err, collection stops and that error is returned. Later items are never visited. Option works the same way: the first None wins.
fn main() {
let good: Result<Vec<i32>, _> = ["1", "2", "3"].iter().map(|s| s.parse::<i32>()).collect();
let bad: Result<Vec<i32>, _> = ["1", "2", "x"].iter().map(|s| s.parse::<i32>()).collect();
println!("{:?}", good); // Ok([1, 2, 3])
println!("{}", bad.is_err()); // true
}This replaces a loop that pushes into a vector and uses ? on each item.
Pitfalls
collectallocates. If you only need to loop over the items once, keep the iterator and skip the intermediateVec.- Collecting into a
HashMapsilently drops duplicate keys. Check the data if keys might repeat. iter()yields references. If you collect.iter()items directly, you getVec<&T>. Use.cloned()or.copied()beforecollectwhen you need owned values.
Making your own type collectable
You can implement FromIterator<A> for your own type. Its single method, from_iter, receives any IntoIterator and returns Self. Once it exists, collect::<YourType>() works.
Exercise
What is the type of result in let result = ["4", "5", "z"].iter().map(|s| s.parse::<u8>()).collect::<Result<Vec<u8>, _>>();, and which value does it hold at runtime?
Show answer
The type is Result<Vec<u8>, ParseIntError>. It holds Err(ParseIntError), because "z" fails to parse. Collection stops there and the successfully parsed 4 and 5 are discarded.