Code Example Template
Deep-Dive System Documentation
The ? Operator: Streamlined Error Propagation
Handling errors using nested match statements can quickly clutter function logic, especially when calling multiple operations that might fail.
The ? operator acts as syntactic sugar for early error returns.
How it works
When appended to a Result or Option expression:
- Success (Ok / Some): Unpacks and returns the inner value, allowing execution to proceed.
- Failure (Err / None): Immediately returns the error from the enclosing function.
use std::fs::File;
use std::io::{self, Read};
fn read_username() -> Result<String, io::Error> {
let mut file = File::open("username.txt")?; // returns early if file missing
let mut username = String::new();
file.read_to_string(&mut username)?; // returns early if read fails
Ok(username)
}
Under the Hood Conversion
The ? operator automatically calls From::from on the error variant. This translates internal errors into the function's official return error type automatically, facilitating easy type conversions.
Quick Reference Guide
let val = func()?; // returns early if Err