rust / intermediate
Snippet
Chaining Results with the ? Operator
The ? operator is a powerful error propagation tool that unwraps Ok values or returns Err values early from functions. It's especially useful when chaining multiple operations that might fail, eliminating verbose match statements and if let chains.
snippet.rs
1
2
3
4
5
6
7
8
9
10
11
12
use std::num::ParseIntError;fn parse_and_add(a: &str, b: &str) -> Result<i32, ParseIntError> {let a: i32 = a.parse()?;let b: i32 = b.parse()?;Ok(a + b)}fn main() {let result = parse_and_add("42", "18");println!("{:?}", result);}
Breakdown
1
use std::num::ParseIntError;
Imports the ParseIntError type for explicit error handling
2
fn parse_and_add(a: &str, b: &str) -> Result<i32, ParseIntError>
Function signature declares the error type explicitly
3
let a: i32 = a.parse()?;
? unwraps the Ok value or returns Err immediately
4
let b: i32 = b.parse()?;
Second parse can also fail, ? handles it the same way
5
Ok(a + b)
Returns the sum wrapped in Ok on success