rust / intermediate
Snippet
Result Type Composition with map and and_then
Result's map method transforms the Ok value while preserving errors. and_then (flat_map) chains computations that return Result, enabling pipeline-style error handling without nested matches. The ? operator works well with both, but map/and_then excel when transforming values within a chain. This functional composition keeps error handling clean and readable.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
use std::num::ParseIntError;fn parse_and_double(s: &str) -> Result<i32, ParseIntError> {s.parse::<i32>().map(|n| n * 2)}fn parse_and_check(s: &str) -> Result<i32, ParseIntError> {s.parse::<i32>().and_then(|n| if n > 0 { Ok(n) } else { Err(ParseIntError::default()) })}fn main() {let inputs = vec!["42", "hello", "-5", "100"];for s in inputs {match parse_and_double(s) {Ok(n) => println!("{} doubled = {}", s, n),Err(_) => println!("Could not parse '{}'", s),}}if let Ok(n) = parse_and_check("50") {println!("50 is positive: {}", n);}}
Breakdown
1
.map(|n| n * 2)
Transforms Ok value: i32 -> i32; Err passes through unchanged
2
.and_then(|n| ...)
Chains a Result-returning closure; must return Result type
3
if n > 0 { Ok(n) } else { Err(...) }
Conditional error creation within and_then chain
4
Err(ParseIntError::default())
Creates error case when validation fails, short-circuiting the chain