Failure with useful information.
Return errors that callers can understand and handle.
01 Understand the contract
Result<T, E> separates successful values from recoverable failures. Parsing input can fail without being a programmer bug, so return an error instead of crashing. The ? operator returns early with an error and unwraps only the success path; the surrounding function must have a compatible return type. Error messages should preserve enough context for the caller to act. Use a domain error enum when callers need structured decisions, and reserve panic for violated invariants or unrecoverable conditions.
02 Make it concrete
This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.
fn quantity(text: &str) -> Result<u32, String> {
let n = text
.parse::<u32>()
.map_err(|_| "not a whole number".to_owned())?;
if n == 0 {
return Err("quantity must be positive".into());
}
Ok(n)
}
fn main() {
println!("{:?}", quantity("3"));
println!("{:?}", quantity("0"));
}Ok(3)
Err("quantity must be positive")- 1
map_err turns a parse error into a domain message.
- 2
? propagates the error without nesting another match.
- 3
A parsed zero is still rejected by the business rule.
cargo run -p lesson_result03 Mind the boundary
04 Your next build
Parse an i32, reject negative values, and test invalid, negative, and valid input.
Reveal one possible solution +
fn nonnegative(s: &str) -> Result<i32, String> {
let n = s.parse::<i32>().map_err(|_| "invalid".to_owned())?;
if n < 0 { Err("negative".into()) } else { Ok(n) }
}
fn main() {
assert!(nonnegative("x").is_err());
assert!(nonnegative("-1").is_err());
assert_eq!(nonnegative("0"), Ok(0));
}05 Check your reasoning
What does ? do on Err?
Understand it.
Then make it yours.
Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.