RUST / CHAPTER 07
Recoverable errors with Result
AdvancedPropagate ordinary failures while preserving useful error information.
By the end of this chapter
- Separate Ok from Err
- Propagate errors with ?
- Avoid panics for expected invalid input
The idea
Enter with enums, match, and function return types understood. Result<T,E> describes either a successful T or an error E. Unlike Option, it can explain why an operation failed. Parsing user text is a normal place for failure: an invalid number should usually become a handled error rather than a panic. Match can provide different behavior for success and failure.
The question mark operator unwraps an Ok value inside a compatible function and returns early on Err, converting the error when an appropriate conversion exists. It does not magically repair input or continue the remaining statements after failure. Build small fallible helpers with explicit return types, then choose a boundary where the application reports the problem. Keep the original error information when it helps a caller recover.
fn twice(text:&str)->Result<i32,std::num::ParseIntError>{
let value=text.parse::<i32>()?;
Ok(value*2)
}
fn main(){match twice("12"){Ok(n)=>println!("{}",n),Err(_)=>println!("invalid")}}24
The parse succeeds, so ? produces twelve and the helper returns Ok(24). Inputs must keep the multiplication within i32 range.
Try it yourself
Write a helper that parses an i32 and returns a Result without discarding the parsing error.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING