Deep-Dive System Documentation
Option: Eliminating Null References
Rust has no null keyword. Instead, the language uses the Option<T> enum to explicitly track when a value might be missing.
Definition
enum Option<T> {
Some(T),
None,
}
Safe Unwrapping
To extract the underlying value safely, avoid .unwrap() (which panics if None). Instead, use safe fallbacks:
let active_window: Option<String> = Some("Chrome".to_string());
// Safe fallback unpacking
let window_name = active_window.unwrap_or_else(|| "Desktop".to_string());
Null Pointer Optimization (NPO)
When wrapping smart pointers or references (such as Box<T> or &T), the compiler represents None as a raw null pointer 0x0. This means Option<&T> is identical in storage size to a standard C raw pointer, offering complete safety at zero performance cost!
Useful Methods
.is_some() -> bool
Returns true if the option is a Some value.
let x: Option<u32> = Some(2);
assert_eq!(x.is_some(), true);
.unwrap() -> T
Extracts the contained value. Use with caution: panics if the value is None.
let x = Some("value");
assert_eq!(x.unwrap(), "value");
.unwrap_or(default: T) -> T
Returns the contained Some value or a provided default value.
assert_eq!(Some("car").unwrap_or("bike"), "car");
assert_eq!(None.unwrap_or("bike"), "bike");
.map<U, F>(f: F) -> Option<U> where F: FnOnce(T) -> U
Maps an Option<T> to Option<U> by applying a function to the contained Some value, leaving a None untouched.
let maybe_num = Some("4");
let maybe_parsed = maybe_num.map(|s| s.parse::<i32>().unwrap());
assert_eq!(maybe_parsed, Some(4));
.and_then<U, F>(f: F) -> Option<U> where F: FnOnce(T) -> Option<U>
Returns None if the option is None, otherwise calls f with the wrapped value and returns the result. Excellent for chaining nullable operations.
let get_num = |s: &str| s.parse::<u32>().ok();
assert_eq!(Some("12").and_then(get_num), Some(12));
assert_eq!(Some("abc").and_then(get_num), None);
Quick Reference Guide
let val: Option<i32> = Some(5);
let unpacked = val.unwrap_or(0);