Skip to content
Tutorials Center
My learning

Topics

Rust Reference ยท Option and Result

Collecting Results and Options

Reference for collecting an iterator of Results into a Result of a collection in Rust: short-circuiting on the first Err, Option, sum, product and partition.

A common task is to run a fallible operation on every item and then either get all the results or learn about the failure. Rust makes this one line: collect can build a Result<Vec<T>, E> straight from an iterator of Result<T, E>. If every item is Ok, you get Ok(vec). At the first Err, iteration stops and you get that error.

The same trick works for Option (Option<Vec<T>>, all Some or the first None), for any collection that implements FromIterator such as HashMap or String, and for sum and product. You pick the shape with a type annotation or the turbofish.

Rust
let r: Result<Vec<i32>, _> = ["1", "2", "3"].iter().map(|s| s.parse::<i32>()).collect();
// Ok([1, 2, 3])

Try it

Rust All or nothing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Rust Keeping every error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Syntax

Rust
impl<A, E, V: FromIterator<A>> FromIterator<Result<A, E>> for Result<V, E>
impl<A, V: FromIterator<A>> FromIterator<Option<A>> for Option<V>
impl<T, U: Sum<T>, E> Sum<Result<T, E>> for Result<U, E>
impl<T, U: Product<T>, E> Product<Result<T, E>> for Result<U, E>
Item Description
collect::<Result<C, E>>() Builds a collection C from Ok values, or returns the first Err.
collect::<Option<C>>() Builds C from Some values, or returns None at the first None.
sum(), product() Add or multiply Ok/Some values; return the first Err/None instead.
try_for_each(f) Runs a fallible closure on every item and returns the first Err.

Returns: a single Result or Option wrapping the collection (or total).

Errors: only the first error is kept. Later items are not examined, so any side effects in the closure for them never happen.

Usage notes

  • Type annotation required. collect cannot guess the target, so write let r: Result<Vec<_>, _> = ... or collect::<Result<Vec<_>, _>>(). Leaving the error type as _ is fine; the compiler infers it.
  • It short-circuits because the iterator is driven lazily: items after the failure are never produced.
  • To keep all errors, use partition as above, or a loop that pushes into two vectors.
  • To skip errors, use filter_map(Result::ok) or .flatten(), as Result is iterable (see ok, err).
  • The ? operator composes with it: let nums = inputs.iter().map(|s| s.parse::<i32>()).collect::<Result<Vec<_>, _>>()?; returns early with the first parse error.
  • Allocation: the collected vector grows as needed; the size hint of an adapter that may stop early is only a lower bound of zero.
  • Order is preserved for Vec, and String receives characters in iteration order.