Rust 1.99 (2024 edition) reference · Option and Result
Rust The ? operator Operator
Propagate errors from functions returning Result or Option: unwrap Ok values and return early on Err.
Rust 1.99 (2024 edition)
Syntax
expr? (in a function returning Result<_, E> where the error converts with From)
Parameters
| Parameter | Description |
|---|---|
Result |
Err(e) returns Err(From::from(e)) from the function. |
Option |
None returns None from the function. |
main() -> Result<(), Box<dyn Error>> |
Use ? in main. |
Examples
fn sum_csv(line: &str) -> Result<i64, std::num::ParseIntError> {
let mut total = 0;
for part in line.split(',') {
total += part.trim().parse::<i64>()?;
}
Ok(total)
}
fn main() {
println!("{:?}", sum_csv("1,2,3"));
println!("{:?}", sum_csv("1,x,3").map_err(|e| e.to_string()));
}
Output
Ok(6)
Err("invalid digit found in string")Run this on your computer — see “Get Started” for setup.
fn first_digit(s: &str) -> Option<u32> {
let c = s.chars().find(|c| c.is_ascii_digit())?;
c.to_digit(10)
}
fn main() {
println!("{:?}", first_digit("abc7d"));
println!("{:?}", first_digit("none"));
}
Output
Some(7) None
Run this on your computer — see “Get Started” for setup.
Related
Result::map_err, unwrap_or_else and ok· Convert or recover from errors: change the error type, fall back to a value, or discard the error as an Option.Option::map, and_then and filter· Transform the value inside an Option without unwrapping it, chain optional steps, or keep it only if a condition holds.- Rust Result and the ? Operator · tutorial