Answer#
Option<T> and Result<T, E> are ordinary enums from the standard library. Because they are types, the compiler forces you to deal with the missing or failed case before you can use the value inside. That is the replacement for null pointer errors and for forgotten error codes.
use std::num::ParseIntError;
fn find_user(id: u32) -> Option<&'static str> {
match id {
1 => Some("Ada"),
2 => Some("Bo"),
_ => None,
}
}
fn parse_and_double(text: &str) -> Result<i32, ParseIntError> {
let n: i32 = text.trim().parse()?; // on error: return it to the caller
Ok(n * 2)
}
fn main() {
println!("{:?} {:?}", find_user(1), find_user(9));
println!("{}", find_user(9).unwrap_or("nobody"));
if let Some(name) = find_user(2) {
println!("found {name}");
}
println!("{:?}", parse_and_double(" 21 "));
println!("{:?}", parse_and_double("x"));
match parse_and_double("x") {
Ok(v) => println!("{v}"),
Err(e) => println!("error: {e}"),
}
}Some("Ada") None
nobody
found Bo
Ok(42)
Err(ParseIntError { kind: InvalidDigit })
error: invalid digit found in stringHow to use them#
matchhandles every case explicitly.if let Some(x) = ...handles one case and ignores the other.unwrap_or(default)supplies a fallback value.unwrap_or_else(|| ...)computes it only when needed.?on aResultgives theOkvalue, or returns theErrfrom the current function at once. The function must itself return aResult(orOption, for?on anOption)..map(...)changes the inside of aSomeorOkand leavesNoneorErralone.
Common mistakes#
- Calling
.unwrap()on input that can really be missing. It panics with a message such ascalled Option::unwrap() on a None value. Reserveunwrapfor cases that cannot fail, or for quick experiments, and useexpect("reason")to leave a message for yourself. - Using
?inmainwithout changing its return type. The error is E0277; the fix isfn main() -> Result<(), Box<dyn std::error::Error>>. - Returning
Err(String)everywhere. A small enum of your own error cases is easier to match on later.
Related questions#
When should a function return an error and when should it panic?#
Return an error for things that can go wrong at run time (bad input, missing file). Panic for bugs, meaning broken assumptions inside the program.