πŸ”€

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

1

Enums can carry different data per variant

2

Option<T> replaces null β€” compiler forces None handling

3

Result<T, E> replaces exceptions β€” errors explicit in types

4

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

Use Cases

DB queries β€” find_by_id() returns Option<User> State machines β€” enum variants represent each state