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
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Collecting an iterator of `Result` items into `Result<Vec<_>, _>` stops at the first error and returns it.
- 2The `?` operator unwraps a successful collection or propagates the parse error up the call stack.
- 3Chaining `map`, `filter`, and `flatten` keeps transformation logic declarative and free of manual loops.
Related explainers
rust
use serde::Deserialize; #[derive(Debug, Deserialize)] #[serde(untagged)]
Parsing flexible JSON shapes with serde
deserialization
enums
json
Intermediate
6 steps
ruby
require "shellwords" require "open3" module Backup
Building safe shell commands in Ruby
shell-out
subprocess
command-injection
Intermediate
7 steps
rust
use std::cmp::{Ordering, Reverse}; use std::collections::BinaryHeap; use std::fs::File; use std::io::{self, BufRead, BufReader, BufWriter, Lines, Write};
K-way merge of sorted logs in Rust
binary-heap
k-way-merge
streaming-io
Intermediate
8 steps
ruby
class UserAgentParser BROWSERS = [ [/Edg\/([\d.]+)/, "Edge"], [/OPR\/([\d.]+)/, "Opera"],
Parsing user-agent strings in Ruby
regex
pattern-matching
lookup-tables
Intermediate
8 steps
javascript
function evaluate(expression) { const tokens = tokenize(expression); let pos = 0;
Building a recursive descent calculator
parsing
recursion
operator-precedence
Intermediate
8 steps
rust
use axum::{ extract::{Path, State}, response::sse::{Event, KeepAlive, Sse}, };
Streaming import progress with SSE in Axum
server-sent-events
streams
watch-channel
Advanced
7 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/collecting-results-in-rust-iterators-explained-rust-041c/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.