Sub topic 14
Collecting an iterator of Results or Options
This chapter assumes you know closures, iterator adapters such as map, and how Result and Option work. It shows how to turn many fallible operations into one outcome.
The problem
Suppose you parse a comma-separated string into numbers. Each parse call returns a Result, so map produces an iterator of Result<i32, ParseIntError>. You usually want one Result<Vec<i32>, _> instead of a pile of separate results.
Collecting into a Result
collect can build a Result<Vec<T>, E> from an iterator whose items are Result<T, E>. The outcome is Ok with every value if all items succeed. Otherwise it is the first Err encountered.
fn main() {
let good: Result<Vec<i32>, _> = "1,2,3".split(',').map(str::parse::<i32>).collect();
let bad: Result<Vec<i32>, _> = "1,x,3".split(',').map(str::parse::<i32>).collect();
println!("{good:?}");
println!("{bad:?}");
}The first line prints Ok([1, 2, 3]). The second prints Err(ParseIntError { kind: InvalidDigit }).
The type annotation matters. collect can build many collection types, so the compiler needs to know the target. You can write Result<Vec<i32>, _> on the variable, or use the turbofish: .collect::<Result<Vec<_>, _>>().
Collecting into an Option
The same idea works for Option. An iterator of Option<T> collects into Option<Vec<T>>. You get Some with all values, or None if any item was None.
fn main() {
let names = ["ann", "bob", "cy"];
let firsts: Option<Vec<char>> = names.iter().map(|n| n.chars().next()).collect();
println!("{firsts:?}");
let with_gap = [Some(1), None, Some(3)];
let all: Option<Vec<i32>> = with_gap.into_iter().collect();
println!("{all:?}");
}This prints Some(['a', 'b', 'c']) and then None.
How it behaves
Collecting into a Result stops at the first error. Items after it are never pulled from the iterator. This is called short-circuiting, and it means side effects in later map closures do not run.
Keeping the failures instead
Sometimes you want to keep going and gather everything. Use partition to split successes from failures, then unwrap each side.
fn main() {
let (oks, errs): (Vec<_>, Vec<_>) = "1,x,3,y"
.split(',')
.map(str::parse::<i32>)
.partition(Result::is_ok);
let numbers: Vec<i32> = oks.into_iter().map(Result::unwrap).collect();
println!("{numbers:?} and {} errors", errs.len());
}The unwrap calls here are safe because partition already separated the Ok values.
Other targets
Collecting works with Sum and Product too. iter.sum::<Result<i32, _>>() adds up the Ok values and returns the first Err if one appears.
Exercise
What does vec![Some(1), Some(2), None].into_iter().collect::<Option<Vec<i32>>>() return, and why?
Show answer
It returns None. Collecting into Option<Vec<_>> gives Some only when every item is Some. A single None makes the whole result None.
Exercise
Write a function parse_all(s: &str) -> Result<Vec<u8>, std::num::ParseIntError> that parses a comma-separated list of numbers and fails on the first invalid entry.
Show answer
fn parse_all(s: &str) -> Result<Vec<u8>, std::num::ParseIntError> { s.split(',').map(|p| p.trim().parse::<u8>()).collect() }