Sub topic 13
Collecting an iterator of Results
This chapter assumes you know how ? works on Result, how From converts errors, and the basics of iterators and closures. Here you will learn how to turn many fallible operations into one Result.
The problem
Suppose you parse a list of strings into integers. Each parse call returns a Result<i32, ParseIntError>. A map over the list therefore produces an iterator of Result values, not an iterator of integers.
You want one of two outcomes. Either you get all the numbers, or you get the first error. A Vec<Result<i32, _>> gives you neither directly. You would have to inspect every element yourself.
Collecting into Result
collect can build a Result<Vec<T>, E> from an iterator whose items are Result<T, E>. The standard library implements FromIterator for Result to make this work.
use std::num::ParseIntError;
fn parse_all(items: &[&str]) -> Result<Vec<i32>, ParseIntError> {
items.iter().map(|s| s.parse::<i32>()).collect()
}
fn main() {
println!("{:?}", parse_all(&["1", "2", "3"]));
println!("{:?}", parse_all(&["1", "x", "3"]));
}The first call prints Ok([1, 2, 3]). The second prints Err(ParseIntError { kind: InvalidDigit }).
The return type tells collect what to build. Without it, the compiler cannot infer the target type and reports an error asking for a type annotation.
How it behaves
collect pulls items one at a time. When it sees an Err, it stops and returns that error. It does not look at the remaining items, and it does not report later errors.
Because iterators are lazy, the closure does not run for items after the first failure. This matters when the closure has side effects or is expensive.
Using ? with collect
collect returns a Result, so you can apply ? to it inside a larger function. You choose the target type with a turbofish or a type annotation.
use std::num::ParseIntError;
fn sum_all(items: &[&str]) -> Result<i32, ParseIntError> {
let numbers = items
.iter()
.map(|s| s.trim().parse::<i32>())
.collect::<Result<Vec<_>, _>>()?;
Ok(numbers.iter().sum())
}
fn main() {
println!("{:?}", sum_all(&["1", " 2 ", "3"]));
}This prints Ok(6). The ? after collect returns early on error, as in earlier chapters.
Other targets
The same idea works for other collections and for Option.
Result<Vec<T>, E>collects values into a vector.Result<HashMap<K, V>, E>collects pairs into a map.Result<(), E>runs every fallible step and discards the values.Option<Vec<T>>returnsNoneif any item isNone.
sum and product also work on iterators of Result. For example, items.iter().map(|s| s.parse::<i32>()).sum::<Result<i32, _>>() returns the total or the first error.
When you need every error
Collecting into Result keeps only the first error. If you want all the failures, for example to report every bad line in a file, use partition and keep both sides.
fn main() {
let items = ["1", "x", "3", "y"];
let (oks, errs): (Vec<_>, Vec<_>) = items
.iter()
.map(|s| s.parse::<i32>())
.partition(|r| r.is_ok());
let numbers: Vec<i32> = oks.into_iter().map(Result::unwrap).collect();
println!("{} parsed, {} failed", numbers.len(), errs.len());
}This prints 2 parsed, 2 failed. The unwrap calls are safe here because partition has already separated out the Ok values.
Exercises
Exercise
What does ["4", "five", "6"].iter().map(|s| s.parse::<i32>()).collect::<Result<Vec<_>, _>>() return, and does the closure run for "6"?
Show answer
It returns Err(ParseIntError { kind: InvalidDigit }). The closure does not run for "6", because collect stops at the first Err.
Exercise
Write a function all_ports(items: &[&str]) -> Result<Vec<u16>, std::num::ParseIntError> that parses every item as a u16 and returns the first error if any item is invalid.
Show answer
fn all_ports(items: &[&str]) -> Result<Vec<u16>, std::num::ParseIntError> { items.iter().map(|s| s.parse::<u16>()).collect() }