🦀 Rust Intermediate

How does error handling with the ? operator work in Rust?

Answer

The ? operator is syntactic sugar for propagating errors from Result and Option values without writing repetitive match boilerplate. When applied to a Result<T, E>, ? either unwraps the Ok(T) value (continuing execution) or immediately returns Err(e) from the enclosing function. For Option<T>, it either unwraps Some(T) or returns None. The ? operator also calls From::from() on the error type, enabling automatic error type conversion. This means you can use ? in a function that returns a different error type as long as the conversion is implemented. It is only usable in functions that return Result or Option. The main() function can return Result<(), Box<dyn Error>> to use ? at the top level.