principlerustMajor
Option<T> and Result<T,E>: encoding absence and failure in the type system
Viewed 0 times
OptionResultNoneSomeOkErrunwrapnull safety
Error Messages
Problem
Developers unfamiliar with Rust try to use null pointers or panic on errors instead of using Option and Result, missing Rust's key safety guarantee.
Solution
Use Option<T> for values that may be absent, and Result<T, E> for operations that may fail:
// Option: Some(value) or None
fn find_user(id: u32) -> Option<String> {
if id == 1 { Some(String::from("Alice")) } else { None }
}
match find_user(1) {
Some(name) => println!("Found: {}", name),
None => println!("Not found"),
}
// Chaining with map, and_then, unwrap_or
let name = find_user(2).unwrap_or_else(|| String::from("Guest"));
// Result: Ok(value) or Err(error)
fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.parse::<u16>()
}
match parse_port("8080") {
Ok(port) => println!("Port: {}", port),
Err(e) => eprintln!("Bad port: {}", e),
}Why
Option and Result make failure states explicit and impossible to ignore. The compiler forces you to handle both branches, eliminating null pointer exceptions and unhandled errors at compile time.
Gotchas
- unwrap() and expect() panic on None/Err — only use them in tests or when the invariant is truly guaranteed
- Option and Result are just enums — any enum method like map, and_then, or_else works on them
- Result<T, E> implements FromResidual, enabling the ? operator for propagation
Revisions (0)
No revisions yet.