Functions and Errors
Result and ?
Parsing That Can Fail
Result<T, E> is Ok or Err. The ? operator returns early on Err, keeping the happy path clean.
Program
Play the program to parse and sum comma-separated numbers.
result.rs
Replay: real traced execution (multi-file project)
fn main() {
match parse_total("10,20,30") {
Ok(total) => println!("{total}"),
Err(e) => println!("error: {e}"),
}
}
fn parse_total(input: &str) -> Result<i32, std::num::ParseIntError> {
let mut total = 0;
for part in input.split(',') {
total += part.parse::<i32>()?;
}
Ok(total)
}
total ← 0
8fn parse_total(input: &str) -> Result<i32, std::num::ParseIntError> {9 let mut tota→ 0l = 0;10 for part in input.split(',') {total ← 10
pass 1 of 39let mut total = 0;10for par"10"t in input.split(',') {11 tota→ 10l += part.parse::<i32>()?;12}All 3 passes — pass 1 is the card above pass parttotal1 "10" 0 → 10 2 "20" 10 → 30 3 "30" 30 → 60 Ok(total)
12 }13 Ok(tota60l)14}
Follow the Parse
- The input text is split into comma-separated pieces.
- Each piece is parsed as a number.
?stops the function at the first bad piece.- If every piece parses, the function returns
Ok(total).
all numbers valid -> add them -> Ok(total)
bad field found -> stop now -> Err(error)
Result
`Result<T, E>` reports success (`Ok`) or failure (`Err`).
? operator
`parse::<i32>()?` returns early if parsing fails.
Ok
`Ok(total)` wraps the successful result.
Exercise: result.rs
Parse three comma-separated numbers, let ? stop on the first bad field, and return the sum on success