Propagating Errors with the ? Operator
Propagating Errors with the ? Operator
The ? operator unwraps Ok values or immediately returns early with Err:
fn parse_and_double(s: &str) -> Result<i32, std::num::ParseIntError> {
let n = s.trim().parse::<i32>()?;
Ok(n * 2)
}
fn main() {
match parse_and_double("42") {
Ok(v) => println!("Result: {}", v),
Err(e) => println!("Parse failed: {}", e),
}
}