Propagate errors with question mark
Quick answer
The ? operator lets a fallible function return early when a step fails, instead of writing a match for every Result. It keeps the successful path readable.
Early return and conversion
For a Result, ? extracts Ok or returns an error from the enclosing compatible function, converting the error if an appropriate From implementation exists. It does not ignore errors. Both examples use the same parse-error type across steps.
use std::num::ParseIntError;fn double(s: &str) -> Result<i64, ParseIntError> { let n: i32 = s.parse()?; Ok(i64::from(n) * 2)}fn main() { println!("{:?}", double("12")); }Expected stdout (not executed):
Ok(24)The successful integer is widened before multiplication.
use std::num::ParseIntError;fn sum(a: &str, b: &str) -> Result<i64, ParseIntError> { let a: i32 = a.parse()?; let b: i32 = b.parse()?; Ok(i64::from(a) + i64::from(b))}fn main() { println!("failed: {}", sum("x", "3").is_err()); }Expected stdout (not executed):
failed: trueThe second parse is skipped when the first fails.
Common mistake
A function returning an ordinary integer cannot directly propagate a Result with ?.
Try it yourself
Extend the sum function to parse three inputs and test a bad last input.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Propagate errors with question mark — practice quiz
Choose one answer per question, then review the explanation.
In a Result-returning function, what does `Ok(6)?` yield when types are compatible?
A function parses two numbers using ?. The first parse fails. Is the second reached?
Why must a function using ? on a Result have a compatible return type?