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 std::sync::Arc; use axum::{ extract::State,
Offloading work with a channel in Axum
background-jobs
message-passing
shared-state
Intermediate
9 steps
ruby
module Api module V1 class BaseController < ActionController::API rescue_from StandardError, with: :render_internal_error
Centralized API error handling in Rails
error-handling
rescue-from
json-api
Intermediate
7 steps
rust
use std::sync::{Arc, Mutex, MutexGuard}; use std::time::Instant; pub struct TimedGuard<'a, T> {
A self-timing mutex guard in Rust
raii
mutex
deref
Advanced
7 steps
javascript
import { parsePhoneNumberFromString } from 'libphonenumber-js'; export class PhoneValidationError extends Error { constructor(message, code) {
Normalizing phone numbers with typed errors
validation
error-handling
custom-errors
Intermediate
6 steps
typescript
import { Injectable, computed, inject, signal } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { firstValueFrom } from 'rxjs';
Optimistic updates with Angular signals
signals
optimistic-updates
state-management
Intermediate
9 steps
python
import os from datetime import datetime, timezone import jwt
JWT bearer auth as a FastAPI dependency
authentication
jwt
dependency-injection
Intermediate
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.