Sub topic 13
Collecting an iterator of Results
This chapter assumes you know how to write closures, call map and collect on iterators, and use ? inside functions that return Result. It also assumes you know what Result<T, E> and Option<T> look like. If ? is still new to you, review the earlier chapters first.
The problem: a list of fallible steps
Parsing a list of strings is a common task. Each parse can fail, so each step produces a Result. If you call map with a fallible function, you do not get a list of numbers. You get an iterator of Result values.
fn main() {
let items = ["1", "2", "x", "4"];
let parsed: Vec<Result<i32, std::num::ParseIntError>> =
items.iter().map(|s| s.parse::<i32>()).collect();
println!("{:?}", parsed);
}This prints a vector with four entries, and the third entry is an Err. The code compiles, but it leaves you to inspect every entry yourself. Usually you want one of two outcomes instead: all the values, or the first error.
Collecting into Result<Vec<_>, _>
The collect method can build many kinds of collections. It works through the FromIterator trait. The standard library implements FromIterator<Result<A, E>> for Result<V, E>, where V is any collection that can be built from A values. So you can ask for a Result<Vec<i32>, ParseIntError> directly.
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 output is:
Ok([1, 2, 3])
Err(ParseIntError { kind: InvalidDigit })The rules are simple:
- If every item is
Ok, the result isOkholding the collection of unwrapped values. - If any item is
Err, the result is the firstErrencountered.
The function body has no ? and no loop. The return type tells collect what to build, so the type annotation is required. Without it the compiler cannot tell which FromIterator implementation you want.
Short-circuiting behavior
Collecting into a Result stops at the first error. The iterator is not consumed past that point. Because iterators are lazy, the closure does not run for the remaining items. You can see this with a side effect.
fn main() {
let items = ["1", "x", "3", "4"];
let result: Result<Vec<i32>, _> = items
.iter()
.map(|s| {
println!("parsing {s}");
s.parse::<i32>()
})
.collect();
println!("{:?}", result);
}Only 1 and x are printed as "parsing". The items 3 and 4 are never touched. This matters in two ways:
- It saves work when later steps are expensive, such as network calls.
- It means you only ever see one error. If you want to report every bad input, this approach is not enough (see below).
Using ? with the collected result
Since collect returns a Result, you can add ? after it when the surrounding function has a compatible error type. This is useful when you need to do more work with the vector.
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 "]));
println!("{:?}", sum_all(&["1", "oops"]));
}Two details are worth noting:
- The turbofish
::<Result<Vec<_>, _>>givescollectits target type. The_placeholders let the compiler infer the element and error types. ?still appliesFromto the error. If the function returned a custom error type withFrom<ParseIntError>, the same line would work unchanged.
How it flows
Other collection targets
The Vec is only one choice. The inner collection can be anything that implements FromIterator for the item type.
use std::collections::HashSet;
use std::num::ParseIntError;
fn unique_numbers(items: &[&str]) -> Result<HashSet<i32>, ParseIntError> {
items.iter().map(|s| s.parse::<i32>()).collect()
}
fn main() {
let set = unique_numbers(&["1", "2", "2", "3"]).unwrap();
println!("{}", set.len());
}This prints 3. You can also collect Result<String, _> from an iterator of Result<char, _>, or Result<(), _> from an iterator of Result<(), _>. The last form is handy for running many fallible actions and caring only about whether they all worked.
use std::io::{self, Write};
fn write_lines(out: &mut impl Write, lines: &[&str]) -> io::Result<()> {
lines.iter().map(|l| writeln!(out, "{l}")).collect()
}
fn main() -> io::Result<()> {
let mut stdout = io::stdout();
write_lines(&mut stdout, &["alpha", "beta"])
}For side effects like this, a plain for loop with ? is often clearer. Use whichever one reads better to you and your team.
The same idea for Option
Option has the matching implementation. Collecting an iterator of Option<T> into Option<Vec<T>> gives Some with all values, or None if any item was None.
fn first_letters(words: &[&str]) -> Option<Vec<char>> {
words.iter().map(|w| w.chars().next()).collect()
}
fn main() {
println!("{:?}", first_letters(&["red", "green"]));
println!("{:?}", first_letters(&["red", ""]));
}The first call returns Some(['r', 'g']). The second returns None because the empty string has no first character.
Keeping every error: partition
Short-circuiting is wrong when users want a full report, for example when validating a form or a data file. In that case, do not collect into a Result. Split the items into successes and failures with partition.
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();
let errors: Vec<_> = errs.into_iter().map(Result::unwrap_err).collect();
println!("numbers: {:?}", numbers);
println!("errors: {}", errors.len());
}The unwrap calpartition already separated the two groups. Each unwrap only sees an Ok, and each unwrap_err only sees an Err`.
If you only want to skip bad items, use filter_map with Result::ok:
fn main() {
let items = ["1", "x", "3"];
let numbers: Vec<i32> = items.iter().filter_map(|s| s.parse().ok()).collect();
println!("{:?}", numbers);
}This silently drops errors. It is fine for best-effort parsing, but it hides data problems, so use it on purpose and not by habit.
Choosing an approach
| Goal | Tool | Behavior on error |
|---|---|---|
| All values or the first error | `collect::<Result<Vec<_>, _>>()` | Stops at the first `Err` |
| All values or nothing, from `Option` | `collect::<Option<Vec<_>>>()` | Stops at the first `None` |
| Every success and every error | `partition` | Processes all items |
| Only the successes | `filter_map(Result::ok)` | Discards errors silently |
| Fallible side effects, with early exit | `for` loop with `?` | Stops at the first `Err` |
Common mistakes
- Missing type annotation.
let v = iter.collect();fails with "type annotations needed". Annotate the variable or use the turbofish. - Wrong error type. Collecting into
Result<Vec<i32>, MyError>requires the iterator's error type to be exactlyMyError.collectdoes not callFrom. If the types differ, convert inside the closure withmap_err, or collect first and then apply?in a function whereFromexists. - Expecting laziness after collect.
collectconsumes the whole iterator right away, up to the first error. It is not lazy. - Using
?inside a closure. A?insidemap(|s| { let n = s.parse::<i32>()?; ... })returns from the closure, not the outer function. The closure must itself return aResult, which is exactly what makes collecting work. The outer function still needs its own?aftercollect.
#[derive(Debug)]
struct AppError(String);
fn parse_all(items: &[&str]) -> Result<Vec<i32>, AppError> {
items
.iter()
.map(|s| s.parse::<i32>().map_err(|e| AppError(format!("{s}: {e}"))))
.collect()
}
fn main() {
println!("{:?}", parse_all(&["7", "bad"]));
}Here map_err inside the closure makes every item a Result<i32, AppError>, so collect matches the function's return type.
Exercises
Exercise
Write a function sum_valid(items: &[&str]) -> Result<i32, std::num::ParseIntError> that returns the sum of all items parsed as i32, or the first parse error. Use collect into a Result.
Show answer
fn sumvalid(items: &[&str]) -> Result<i32, std::num::ParseIntError> { let numbers = items .iter() .map(|s| s.parse::<i32>()) .collect::<Result<Vec<>, _>>()?; Ok(numbers.iter().sum()) }
Exercise
Given ["4", "5", "six", "seven"] and .map(|s| s.parse::<i32>()).collect::<Result<Vec<i32>, _>>(), which error is returned, and is the closure called for "seven"?
Show answer
The error for "six" is returned (an InvalidDigit ParseIntError). The closure is not called for "seven" because collect stops at the first Err.
Exercise
You need to validate a CSV column and show the user every invalid value, not only the first. Should you collect into Result<Vec<_>, _>? What do you use instead?
Show answer
No. Collecting into a Result stops at the first error. Use partition (or a loop that pushes errors into a separate Vec) so every item is processed and all errors are reported.