Result and ? in Rust
Recoverable errors, and the ? early-return operator.
fn parse_sum(a: &str, b: &str) -> Result<i32, std::num::ParseIntError> {
let x: i32 = a.parse()?;
let y: i32 = b.parse()?;
Ok(x + y)
}
fn main() {
match parse_sum("3", "4") {
Ok(total) => println!("sum: {total}"),
Err(e) => println!("error: {e}"),
}
}
How it works
parse()?returns early on an error.- The function's error type is the parse error.
matchhandlesOkandErrat the call site.
Keywords and builtins used here
ErrOkResultfni32letmainmatchparse_sumstr
The run, in numbers
- Lines
- 12
- Characters to type
- 252
- Tokens
- 101
- Three-star pace
- 100 tpm
At the three-star pace of 100 tokens a minute, this run takes about 61 seconds.
Step 1 of 4 in Result & the ? operator, step 4 of 15 in Error handling.