capypad
0 day streak
rust / beginner
Snippet

The ? Operator for Error Propagation

The ? operator is syntactic sugar for error handling. When used on a Result, it unwraps the Ok value if successful, or immediately returns the Err value from the current function if an error occurred. This eliminates verbose match chains and makes error propagation feel like a natural part of the computation flow. The ? operator only works in functions that return Result or Option.

snippet.rs
rust
1
use std::num::ParseIntError;\n\nfn parse_and_double(s: &str) -> Result<i32, ParseIntError> {\n let num: i32 = s.parse::<i32>()?;\n Ok(num * 2)\n}\n\nfn parse_and_add(s: &str, t: &str) -> Result<i32, ParseIntError> {\n let a = s.parse::<i32>()?;\n let b = t.parse::<i32>()?;\n Ok(a + b)\n}\n\nfn main() {\n match parse_and_double("42") {\n Ok(result) => println!("Doubled: {}", result),\n Err(e) => println!("Error: {}", e),\n }\n}
Breakdown
1
s.parse::<i32>()?
Attempts to parse string into i32; ? returns error if parse fails
2
Ok(num * 2)
Wraps the successful calculation in Ok to match the return type
3
fn parse_and_add
Chains multiple ? operators — first error stops execution and returns
4
Result<i32, ParseIntError>
Function signature declares possible error type for the compiler
5
match parse_and_double("42")
Demonstrates calling the function and handling the Result manually