10.9 Enums as the Basis for Option and Result
Rust’s core Option<T> and Result<T, E> types are prime examples of the power of enums.
10.9.1 The Option<T> Enum: Handling Absence
Replaces NULL safely, encoding potential absence.
#![allow(unused)] fn main() { enum Option<T> { Some(T), // Represents presence of a value of type T None, // Represents absence of a value } }
- No Null Errors: Forces explicit handling of
Nonevia pattern matching or methods. - Type Safety:
Option<String>is distinct fromString. Requires explicit unwrapping.
Covered in detail in Chapter 14.
10.9.2 The Result<T, E> Enum: Handling Errors
Standard way to represent operations that can succeed (Ok) or fail (Err).
#![allow(unused)] fn main() { enum Result<T, E> { Ok(T), // Represents success, containing a value T Err(E), // Represents failure, containing an error E } }
- Explicit Errors: Type system signals potential failure; encourages handling both
OkandErr. - Clear Paths: Separates success value (
T) from error value (E).
Covered in detail in Chapter 15.