Sub topic 14
Collecting an iterator of Results or Options
This chapter assumes you can write closures and iterator chains, and that you know Option, Result, map, and the ? operator from earlier chapters. It covers a common situation. You run a fallible step over many items and want one outcome for the whole batch, not a pile of individual Result values.
The problem: an iterator of Results
Mapping a fallible function over a sequence produces an iterator whose items are Result values. Calling .collect() as you normally would gives a Vec<Result<i32, ParseIntError>>. That type is awkward, because you have to check every element before you can use any value.
Usually you want the opposite shape: a Result that holds a whole Vec. Rust provides it through the FromIterator trait, which Result and Option implement for this purpose.
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:?}");
}This prints:
Ok([1, 2, 3])
Err(ParseIntError { kind: InvalidDigit })If every item is Ok, you get Ok containing the collection. If any item is Err, you get the first Err and nothing else.
The target type chooses the behavior
collect is generic over its return type, so the annotation decides what happens. You can write it on the let binding or with a turbofish (::<...>).
| Iterator item | Collect target | Result |
|---|---|---|
| `Result<T, E>` | `Vec<Result<T, E>>` | Every item kept, nothing combined |
| `Result<T, E>` | `Result<Vec<T>, E>` | `Ok(all values)` or the first `Err` |
| `Option<T>` | `Option<Vec<T>>` | `Some(all values)` or `None` |
| `Result<(K, V), E>` | `Result<HashMap<K, V>, E>` | `Ok(map)` or the first `Err` |
The first row is the default shape. The other rows ask collect to merge the items into one outcome. Without an annotation the compiler reports that it cannot infer the type.
Short-circuiting is real
Collection stops at the first failure. The iterator is lazy, so the items after the failure are never produced. A function with side effects shows this.
fn check(n: i32) -> Result<i32, String> {
println!("checking {n}");
if n < 0 {
Err(format!("{n} is negative"))
} else {
Ok(n)
}
}
fn main() {
let r: Result<Vec<i32>, String> = [1, 2, -3, 4, -5].into_iter().map(check).collect();
println!("{r:?}");
}The output is:
checking 1
checking 2
checking -3
Err("-3 is negative")The values 4 and -5 are never checked. Two consequences follow:
- You only ever see one error, the first. If you want a report of all bad inputs, you need a different approach (see below).
- Side effects inside the mapped function stop part-way. If
checkwrote to a database, some rows would be written and others not.
Collecting Options
Option works the same way, with None playing the role of Err. Use it when "any missing item makes the whole batch invalid".
fn main() {
let words = ["apple", "banana", "cherry"];
let initials: Option<Vec<char>> = words.iter().map(|w| w.chars().next()).collect();
println!("{initials:?}");
let with_empty = ["apple", "", "cherry"];
let initials: Option<Vec<char>> = with_empty.iter().map(|w| w.chars().next()).collect();
println!("{initials:?}");
}This prints Some(['a', 'b', 'c']) and then None. None carries no information about which item was empty. If you need that, use a Result with an error that names the item.
Other collections
The Vec is only one choice. Any collection that implements FromIterator for the item type can sit inside the Result. This example builds a HashMap from key=value pairs.
use std::collections::HashMap;
fn parse_pair(s: &str) -> Result<(String, u16), String> {
let (k, v) = s
.split_once('=')
.ok_or_else(|| format!("no '=' in {s:?}"))?;
let v = v.parse::<u16>().map_err(|e| format!("bad value {v:?}: {e}"))?;
Ok((k.to_string(), v))
}
fn main() {
let ok: Result<HashMap<String, u16>, String> =
"a=1,b=2".split(',').map(parse_pair).collect();
println!("{:?}", ok.map(|m| m.len()));
let bad: Result<HashMap<String, u16>, String> =
"a=1,b".split(',').map(parse_pair).collect();
println!("{bad:?}");
}The output is Ok(2) and then Err("no '=' in \"b\""). parse_pair uses ok_or_else to turn an Option into a Result and ? to propagate both failures, so each stage from earlier chapters appears here.
The same rule applies to Result<(), E>. Collecting an iterator of Result<(), E> into Result<(), E> runs every step until the first failure and keeps no values. This is a handy way to run a list of checks.
Using ? with collect
Because the collected value is an ordinary Result, you can follow it with ?. This keeps the function body flat.
use std::num::ParseIntError;
fn parse_all(input: &str) -> Result<Vec<i32>, ParseIntError> {
let values = input
.split_whitespace()
.map(str::parse::<i32>)
.collect::<Result<Vec<_>, _>>()?;
Ok(values)
}
fn main() {
println!("{:?}", parse_all("10 20 30"));
println!("{:?}", parse_all("10 abc 30"));
}The _ placeholders let the compiler fill in the element and error types. You only have to state the outer shapes, Result and Vec. If the function returned a custom error type with a From<ParseIntError> implementation, the ? would convert the error automatically.
sum and product work too
Result and Option also implement Sum and Product. Adding up parsed numbers can fail as a whole.
use std::num::ParseIntError;
fn main() {
let total: Result<i32, ParseIntError> = "4 5 6".split_whitespace().map(str::parse::<i32>).sum();
let broken: Result<i32, ParseIntError> = "4 x 6".split_whitespace().map(str::parse::<i32>).sum();
println!("{total:?}");
println!("{broken:?}");
}This prints Ok(15) and then Err(ParseIntError { kind: InvalidDigit }). As with collect, the sum stops at the first Err.
When you do not want all-or-nothing
Sometimes one bad item should not discard the rest. There are two usual choices.
Skip failures silently. filter_map(Result::ok) keeps only the successes. flatten() does the same, because Result and Option are themselves iterators of zero or one item.
Keep the successes and record the failures. Capture a list in the closure and push each error into it.
fn main() {
let inputs = ["1", "x", "3", "y"];
let mut errors: Vec<String> = Vec::new();
let values: Vec<i32> = inputs
.iter()
.filter_map(|s| {
s.parse::<i32>()
.map_err(|e| errors.push(format!("{s}: {e}")))
.ok()
})
.collect();
println!("{values:?}");
println!("{errors:?}");
}The output is:
[1, 3]
["x: invalid digit found in string", "y: invalid digit found in string"]The closure borrows errors mutably, so you can only read errors after collect has finished and the closure is gone. Here that happens at the end of the let values statement.
Common mistakes
- Missing type annotation.
collect()with no target type fails to compile. Annotate the binding or usecollect::<Result<Vec<_>, _>>(). - Annotating the wrong shape.
Vec<Result<T, E>>andResult<Vec<T>, E>are different types with different behavior. The second one short-circuits. - Expecting every error. The combined
Resultholds only the firstErr. Use the error-collecting pattern above when you need them all. - Side effects in the mapped function. Because collection stops early, work done by later items never happens.
- Mixing Option and Result in one chain. Convert one to the other first, for example with
ok_or, so every item has the same type.
Exercise
What does this code print, and why? let r: Option<Vec<u32>> = ["1", "2", "three", "4"].iter().map(|s| s.parse().ok()).collect(); println!("{r:?}");
Show answer
It prints None. Each parse().ok() gives Some(n) for the valid numbers and None for "three". Collecting into Option<Vec<u32>> returns None as soon as one item is None. The Vec of the other values is discarded, and "4" is never examined.
Exercise
You have lines: Vec<&str> and want every line that parses as an i32, and also a list of the lines that failed. Which pattern fits, and why not collect::<Result<Vec<_>, _>>()?
Show answer
Use filter_map with a captured Vec for failures, as in the chapter. Collecting into Result<Vec<_>, _> stops at the first bad line, so you would lose the later valid values and see only one error.