rust 21 lines · 7 steps

Collecting Results in Rust iterators

Rust's iterators can gather fallible operations into a single Result, short-circuiting on the first error.

Explained by highlit
1use std::num::ParseIntError;
2 
3fn parse_line(line: &str) -> Result<Vec<i64>, ParseIntError> {
4 line.split(',')
5 .map(str::trim)
6 .filter(|token| !token.is_empty())
7 .map(|token| token.parse::<i64>())
8 .collect()
9}
10 
11fn sum_all_lines(input: &str) -> Result<i64, ParseIntError> {
12 let numbers: Vec<i64> = input
13 .lines()
14 .map(parse_line)
15 .collect::<Result<Vec<_>, _>>()?
16 .into_iter()
17 .flatten()
18 .collect();
19 
20 Ok(numbers.iter().sum())
21}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1Collecting an iterator of `Result` items into `Result<Vec<_>, _>` stops at the first error and returns it.
  2. 2The `?` operator unwraps a successful collection or propagates the parse error up the call stack.
  3. 3Chaining `map`, `filter`, and `flatten` keeps transformation logic declarative and free of manual loops.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Collecting Results in Rust iterators — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code