rust / intermediate
Snippet
Result<T, E> for Recoverable Errors
Result<T, E> represents recoverable errors: Ok(T) for success, Err(E) for failure. The ? operator propagates errors early, returning from the function immediately on Err. This is idiomatic Rust error handling — explicit, composable, and zero-cost. Unlike exceptions, errors are values that can be manipulated like any other data.
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
use std::num::ParseIntError;fn parse_and_double(s: &str) -> Result<i32, ParseIntError> {let num: i32 = s.parse()?;Ok(num * 2)}fn main() {// Using ? operator for error propagationmatch parse_and_double("42") {Ok(n) => println!("Doubled: {}", n),Err(e) => println!("Parse error: {}", e),}// Chaining with and_thenlet result = parse_and_double("10").and_then(|n| parse_and_double(&n.to_string()));match result {Ok(n) => println!("Chained result: {}", n),Err(_) => println!("Chain failed"),}}
Breakdown
1
fn parse_and_double(s: &str) -> Result<i32, ParseIntError>
Function returns Result: success value or error type
2
s.parse::<i32>()?
? operator returns early if Err, unwraps Ok value if success
3
Ok(num * 2)
Wraps successful computation in Ok variant
4
.and_then(|n| ... )
Chains operations, passing Ok value or passing Err through
5
Err(_) => println!("Chain failed")
Wildcard pattern catches any error variant