Enum, Option, Result β Algebraic Data Types in Rust
A type system that creates a null-free world
C/Java enums are integer constant lists. Rust enums let each variant carry different typed data β called Algebraic Data Types (ADTs).
Option<T> = Some(T) | None. Replaces null. Using Option where values might be absent forces the compiler to handle None. NullPointerException eliminated at the source.
Result<T, E> = Ok(T) | Err(E). Replaces exceptions. Foundation of error handling covered earlier.
These two types appear nearly everywhere in Rust code. Getting comfortable with them is the key to becoming fluent in Rust.
Key Points
Enums can carry different data per variant
Option<T> replaces null β compiler forces None handling
Result<T, E> replaces exceptions β errors explicit in types
Handle all variants exhaustively with match
Pros
- ✓ Eliminates null/exception runtime errors at source
- ✓ No missing branches thanks to exhaustive match checking
Cons
- ✗ Boilerplate to unwrap Option/Result