skip to content

In Rust, what happens when you collect an iterator of Result<T, E> into Result<Vec<T>, E>, and when is that the wrong choice?

level: seniorimportance: should knowfreq 45%

answer

  1. FromIterator for Result
  2. first Err wins
  3. remaining items never pulled
  4. collect does not convert errors
  5. Vec<Result> keeps every failure

basics

~20 s

Collecting into Result<Vec<T>, E> returns Ok with every value if all items are Ok, or the first Err; it stops pulling items at that Err. It is wrong when every failure must be reported or later items must still run.

solid answer

~40 s

Std implements `FromIterator<Result<A, E>>` for `Result<V, E>` whenever `V: FromIterator<A>`. Its doc says that if an element is an `Err`, no further elements are taken and that `Err` is returned; otherwise you get `Ok` of the collected container. So `rows.iter().map(|r| r.parse::<u32>()).collect::<Result<Vec<_>, _>>()` short-circuits on the first bad row, drops the values gathered so far, and never runs the closure on later rows. The error type must match exactly: `collect` applies no `From` conversion, so a mismatch is E0277 and needs `map_err`. Choose it for all-or-nothing input. When you must report every bad row, or every item must be processed regardless, collect into `Vec<Result<T, E>>` and split the outcomes instead.

code

rust · 23 lines
rust
use std::num::ParseIntError;

fn main() {
    let ages = ["36", "x1", "52", "zz"];

    // Result<Vec<_>, E>: stops pulling at the first Err and returns it
    let all: Result<Vec<u32>, ParseIntError> = ages
        .iter()
        .inspect(|raw| println!("parsing {raw}"))
        .map(|raw| raw.parse::<u32>())
        .collect();
    println!("all = {all:?}");

    // Vec<Result<_, _>>: keeps every outcome, so every failure can be reported
    let each: Vec<Result<u32, ParseIntError>> = ages.iter().map(|r| r.parse()).collect();
    let good: Vec<u32> = each.iter().filter_map(|r| r.as_ref().ok().copied()).collect();
    let bad: Vec<String> = each.iter().filter_map(|r| r.as_ref().err()).map(|e| e.to_string()).collect();
    println!("good = {good:?}, bad = {bad:?}");

    // Summing Results short-circuits the same way
    let total: Result<u32, ParseIntError> = ["1", "2", "3"].iter().map(|r| r.parse::<u32>()).sum();
    println!("total = {total:?}");
}

go deeper

for a junior

Recall that an iterator of Results can be collected into one Result holding a Vec, and that one Err makes the whole thing an Err.

for a middle

Explain FromIterator for Result: the first Err stops the iteration and is returned, and the target type must be annotated.

for a senior

Reason about laziness and side effects: items after the Err never run, earlier effects persist, and validation feedback needs Vec<Result> instead.

for a principal

Set the batch-failure policy with the product: reject on first error, report every error, or skip and count, and make the type say which.

## The impl behind the trick `Iterator::collect` builds any type that implements `FromIterator<Item>`. Core contains: ```rust impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E> ``` and the matching impl for `Option`. The doc comment states the behaviour: it takes each element; if it is an `Err`, no further elements are taken and the `Err` is returned; should no `Err` occur, a container with the values of each `Result` is returned. `V` can be any collection that implements `FromIterator<A>`: a `Vec<T>`, a `HashMap<K, V>` from pairs, a `String` from chars. `Sum` and `Product` are implemented for `Result` in the same spirit, so `.sum::<Result<u32, _>>()` adds values until the first error. ## What actually runs Take a batch of age strings from a user import: `["36", "x1", "52", "zz"]`. With an `inspect` step printing each item: 1. `"36"` is pulled, parsed to `Ok(36)` and pushed into the vector being built. 2. `"x1"` is pulled and parses to `Err(InvalidDigit)`. The adapter records the error and stops yielding. 3. `"52"` and `"zz"` are **never pulled**: `inspect` prints nothing for them and `parse` never runs on them. 4. The partly built `Vec` holding `36` is dropped and `collect` returns `Err(ParseIntError { kind: InvalidDigit })`. Laziness is the point: the iterator chain is driven by `collect`, and once the error is seen nothing upstream advances. Any side effect in an earlier `map` (a write, a network call, an insert) has already happened for the items before the error and has not happened for the items after it. ## Compile-time requirements - **The target type must be named.** `let all = it.collect();` fails with E0283, "type annotations needed", because many types implement `FromIterator`. Annotate the binding or use the turbofish, `collect::<Result<Vec<_>, _>>()`. - **The error type must match exactly.** Declaring `Result<Vec<u32>, String>` while items are `Result<u32, ParseIntError>` fails with E0277: "a value of type `Result<Vec<u32>, String>` cannot be built from an iterator over elements of type `Result<u32, ParseIntError>`". `collect` applies no `From` conversion; add `.map_err(...)` inside the chain. ## All-or-nothing versus every failure | Goal | Collect into | Behaviour | |---|---|---| | Reject the whole batch on the first bad item | `Result<Vec<T>, E>` | stops at the first `Err`, returns it | | Report every bad item | `Vec<Result<T, E>>`, then split | processes every item, keeps every outcome | | Skip bad items silently | `filter_map(Result::ok)` into `Vec<T>` | processes every item, discards errors | Short-circuiting is the wrong choice when: - A user uploads a file and expects **every** invalid row listed, not only the first one, so they can fix it in one pass. - Each item has an independent side effect that must be attempted regardless of its neighbours, such as sending notifications. - Partial work before the error must be rolled back, which the collect itself does not do: it only drops the values it gathered, not effects they caused. To keep every outcome, collect into `Vec<Result<T, E>>` and split it, for example `each.iter().filter_map(|r| r.as_ref().ok().copied())` for the values and `filter_map(|r| r.as_ref().err())` for the errors, or `Iterator::partition` with `Result::is_ok`. ## Common mistakes - Assuming every element is still parsed and only the first error is reported; later elements are not touched. - Expecting `collect` to convert error types the way the question-mark operator does. - Using the all-or-nothing form for validation feedback, so users fix one error per round trip. - Silently discarding errors with `filter_map(Result::ok)` when the failures should at least be counted or logged. How `collect` and `FromIterator` work for ordinary collections, and the turbofish in general, belong to the lesson on iterator adapters and consumers; this question is about what the `Result` and `Option` impls add.

  • In Rust, does collecting into Result<Vec<T>, E> undo side effects from items processed before the first Err?
    No. It drops the values already gathered into the partial `Vec`, but anything an earlier `map` closure did, such as writing a row or sending a request, has already happened. If the batch must be atomic, wrap it in a transaction or validate everything first, then apply effects only after the collect returns `Ok`.
  • Why does let all = iter.map(|s| s.parse::<u32>()).collect(); fail to compile in Rust?
    `collect` is generic over any `B: FromIterator<Item>`, and many types qualify: `Vec<Result<u32, _>>`, `Result<Vec<u32>, _>`, `Result<HashSet<u32>, _>`. With no annotation rustc cannot choose and reports E0283, type annotations needed. Annotate the binding or write `collect::<Result<Vec<_>, _>>()`.

  • Collecting into Result<Vec<T>, E> still parses every element before returning
  • collect converts the item error type into the declared error type via From
  • The returned Err is the last error in the iterator
  • Short-circuiting collect rolls back side effects of earlier items
  • Result<Vec<T>, E> is the right shape for reporting all validation errors