10.9 Enums as the Basis for Option
and Result
The Rust standard library relies heavily on enums. Two crucial examples are Option
and Result
.
10.9.1 The Option
Enum
#![allow(unused)] fn main() { enum Option<T> { Some(T), None, } }
- No Null Pointers:
Option<T>
encodes the possibility of either having a value (Some
) or not (None
). - Pattern Matching: Forces you to handle the absence of a value explicitly.
10.9.2 The Result
Enum
#![allow(unused)] fn main() { enum Result<T, E> { Ok(T), Err(E), } }
- Error Handling: Distinguishes success (
Ok
) from failure (Err
). - Pattern Matching: Encourages explicit error handling.
We’ll discuss these types further when covering optional values and error handling in Chapters 14 and 15.