Result and recoverable errors
Quick answer
Use Result<T, E> when an operation can fail for a reason the caller may need to handle. It separates success data from failure data without requiring an exception.
Match both outcomes
Ok(value) carries a successful value of type T; Err(error) carries failure of type E. A match can bind either payload. Parsing a string into an integer returns Result because arbitrary text may not represent a valid number.
fn main() { for input in ["42", "tea"] { match input.parse::<i32>() { Ok(n) => println!("number: {n}"), Err(_) => println!("invalid number"), } }}Expected stdout (not executed):
number: 42invalid numberInvalid input is reported without a panic.
fn seats(n: i32) -> Result<i32, &'static str> { if n > 0 { Ok(n) } else { Err("positive count required") }}fn main() { println!("{:?}", seats(0)); }Expected stdout (not executed):
Err("positive count required")The function makes its input rule explicit.
Common mistake
Do not use unwrap for expected invalid input; it panics on Err.
Try it yourself
Write a validator returning Result for a temperature between zero and one hundred.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Result and recoverable errors — practice quiz
Choose one answer per question, then review the explanation.
What variant is returned by parsing `"42"` as u32?
Why does `"-1".parse::<u32>()` fail?
What should matching Err(e) allow you to do?