Option and Result
Option says a value might be missing and Result says an operation might fail, and Rust makes you handle both cases before you can use the value.
Handle absent values and failures explicitly instead of inventing a sentinel value.
Search the catalogue for a title it does not hold. Type letters where a card number should go. Many languages answer with null or an exception that the caller may forget to handle. Rust has neither. It uses two ordinary enums, and the type system will not let you ignore them.
The rule
Maybe missing →
Option; might fail →Result. Handle both arms before use.
Both are enums from the standard library, always in scope:
enum Option<T> { Some(T), None }
enum Result<T, E> { Ok(T), Err(E) }Option<T>: a value that may be absent, with no reason needed.
fn find(shelf: &[Book], title: &str) -> Option<usize> {
shelf.iter().position(|b| b.title == title)
}Result<T, E>: an operation that can fail, and E says why.
let card: Result<u32, _> = "1042".parse::<u32>(); // Ok(1042)
let bad: Result<u32, _> = "10x2".parse::<u32>(); // Err(ParseIntError)An Option<u32> is not a u32. You cannot add to it or print it as a number until you open it:
match "10x2".parse::<u32>() {
Ok(card) => println!("lending to card {card}"),
Err(e) => println!("that is not a card number: {e}"),
}
if let Some(i) = find(&shelf, "Iron Tides") {
println!("found at position {i}");
}Handy methods instead of a full match:
unwrap_or(default): the value, or a fallback.input.parse::<u32>().unwrap_or(0).unwrap(): the value, or panic (crash) onNone/Err.expect("message"): likeunwrap, with your message in the panic.ok()turns aResultinto anOption;ok_or(err)goes the other way.