Sub topic 12
Gathering results with collect
This chapter covers collect, the consumer that turns an iterator back into a collection. It assumes you know the Iterator trait, adapters such as map and filter, generics with trait bounds, and Option and Result.
collect and FromIterator
collect is a method on Iterator that consumes the iterator and builds a value from its items. Its return type is a generic parameter:
fn collect<B: FromIterator<Self::Item>>(self) -> Bcollect does not know what to build. The type B decides that. Any type that implements FromIterator<Item> can be a target, and collect just calls B::from_iter(self).
Because the return type is generic, the compiler must be able to work out B. You can name it in three ways:
- Annotate the binding:
let v: Vec<i32> = ...collect(); - Use the turbofish on
collect:...collect::<Vec<i32>>(). - Let the surrounding code fix it, such as a function return type or a parameter type.
You can leave the element type as _ when the compiler can infer it. Vec<_> says "a Vec, you work out what is inside".
fn main() {
let squares = (1..=4).map(|n| n * n).collect::<Vec<_>>();
println!("{:?}", squares); // [1, 4, 9, 16]
}Common target types
The standard library implements FromIterator for most collections. The item type must match what the collection stores.
| Target | Item type required |
|---|---|
| `Vec<T>`, `VecDeque<T>`, `HashSet<T>`, `BTreeSet<T>` | `T` |
| `HashMap<K, V>`, `BTreeMap<K, V>` | `(K, V)` |
| `String` | `char`, `&str`, `String`, or `&char` |
| `Result<C, E>` | `Result<T, E>`, where `C: FromIterator<T>` |
| `Option<C>` | `Option<T>`, where `C: FromIterator<T>` |
| `()` | `()` |
use std::collections::{HashMap, HashSet};
fn main() {
let words = ["apple", "bob", "cat", "bob"];
let list: Vec<&str> = words.iter().copied().collect();
let unique: HashSet<&str> = words.iter().copied().collect();
let lengths: HashMap<&str, usize> = words.iter().map(|w| (*w, w.len())).collect();
let shouted: String = words.iter().map(|w| w.to_uppercase()).collect();
println!("{}", list.len()); // 4
println!("{}", unique.len()); // 3
println!("{}", lengths["apple"]); // 5
println!("{}", shouted); // APPLEBOBCATBOB
}Two details matter here. copied() turns an iterator of &&str into an iterator of &str, so the collection holds &str instead of a reference to a reference. Collecting into a HashSet or HashMap also drops duplicates. When a HashMap receives the same key twice, the later pair replaces the earlier one.
use std::collections::HashMap;
fn main() {
let m: HashMap<&str, i32> = [("a", 1), ("a", 2)].into_iter().collect();
println!("{}", m["a"]); // 2
}Collecting Results and Options
Result<C, E> implements FromIterator<Result<T, E>> when C implements FromIterator<T>. This lets you turn an iterator of fallible items into one fallible collection. The first Err ends the collection and becomes the result. If every item is Ok, you get Ok holding the collected values.
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 })
}Here the function's return type tells the compiler what collect must build, so no annotation is needed inside the body.
The short circuit is observable. After the first error, the adapter pipeline is not driven any further:
fn main() {
let mut seen = 0;
let r: Result<Vec<i32>, _> = ["1", "x", "3"]
.iter()
.map(|s| {
seen += 1;
s.parse::<i32>()
})
.collect();
println!("{} {}", r.is_err(), seen); // true 2
}Option works the same way. Collecting Option<Vec<T>> gives Some(vec) only if every item was Some, and None as soon as one item is None.
fn main() {
let all: Option<Vec<u32>> = ["1", "2"].iter().map(|s| s.parse::<u32>().ok()).collect();
let some_bad: Option<Vec<u32>> = ["1", "q"].iter().map(|s| s.parse::<u32>().ok()).collect();
println!("{:?} {:?}", all, some_bad); // Some([1, 2]) None
}Splitting results: unzip and partition
Two other consumers build collections, but into two outputs instead of one.
unzipconsumes an iterator of pairs and returns a pair of collections.partitiontakes a predicate and sorts items into a "true" collection and a "false" collection.
fn main() {
let pairs = vec![(1, 'a'), (2, 'b'), (3, 'c')];
let (nums, letters): (Vec<i32>, Vec<char>) = pairs.into_iter().unzip();
println!("{:?} {:?}", nums, letters); // [1, 2, 3] ['a', 'b', 'c']
let (even, odd): (Vec<i32>, Vec<i32>) = (1..=6).partition(|n| n % 2 == 0);
println!("{:?} {:?}", even, odd); // [2, 4, 6] [1, 3, 5]
}Both still require type annotations, because the compiler cannot guess the two collection types.
Implementing FromIterator for your own type
To make collect work for a type of your own, implement FromIterator<Item>. Since the 2021 edition the trait is in the prelude, so no import is needed.
struct Stats {
count: usize,
total: i64,
}
impl FromIterator<i64> for Stats {
fn from_iter<I: IntoIterator<Item = i64>>(iter: I) -> Self {
let mut stats = Stats { count: 0, total: 0 };
for n in iter {
stats.count += 1;
stats.total += n;
}
stats
}
}
fn main() {
let stats: Stats = vec![4, 5, 6].into_iter().collect();
println!("{} {}", stats.count, stats.total); // 3 15
}The parameter is IntoIterator, not Iterator, so from_iter can also be called directly with a Vec or an array. A type that already exists and should grow in place can implement Extend as well. extend adds items to an existing collection, while collect builds a new one.
Common errors
Missing type information. This fails to compile with "type annotations needed":
fn main() {
let v = (1..4).map(|n| n * 2).collect();
println!("{:?}", v);
}Fix it with let v: Vec<i32> = ... or collect::<Vec<_>>().
Item type mismatch. The compiler reports that FromIterator<&i32> is not implemented for Vec<i32> when you call iter() and collect into owned values. Add .copied() or .cloned(), or switch to into_iter(). Both copied and cloned produce owned values. The difference is that copied works only for Copy types, while cloned calls clone and so also works for String.
Collecting just to iterate again. Writing .collect::<Vec<_>>().iter() in the middle of a chain allocates for no reason. Keep the chain lazy and collect only when you need to store the data or traverse it more than once.
Wrong shape for a map. HashMap needs (K, V) tuples. A map that returns only the key fails with an error that FromIterator<K> is not implemented for HashMap.
Exercise
Write a function scores(input: &str) -> Result<HashMap<String, u32>, ParseIntError> that reads text such as "ann=10,bob=7" and builds a map from each name to its score. Why does the whole call fail if one score is not a number?
Show answer
Use split(','), then split_once('=') on each piece, and parse the score. Sketch: input.split(',').map(|pair| { let (name, score) = pair.split_once('=').unwrap_or((pair, "")); score.parse::<u32>().map(|n| (name.to_string(), n)) }).collect(). The closure returns Result<(String, u32), ParseIntError>. Collecting an iterator of those into Result<HashMap<_, _>, _> works because HashMap<K, V> implements FromIterator<(K, V)>, and Result forwards that implementation. The first Err ends the collection and is returned as the result, so one bad score makes the whole call fail.
Exercise
What does let r: Option<Vec<i32>> = vec![Some(1), None, Some(3)].into_iter().collect(); produce, and how many items does the iterator yield before collection stops?
Show answer
It produces None. Collection stops at the second item, the first None, so the third item is never read.