QUICK START:HTMLCSSJavaScriptTypeScriptPythonSQLReactNext.jsNode.jsDSASystem DesignDevOpsCybersecurityAI / ML
Advanced 18 min readModule: Module 7: Enums, Pattern Matching & Option

Enums with Data, Pattern Matching & Option<T>

Eliminate null pointer bugs using Option<T> (Some/None) and exhaustive 'match' expressions.

What You Will Learn in This Lesson

  • Enums that hold arbitrary payload data in each variant
  • Why Rust has NO null primitive (uses Option<T> instead)
  • Exhaustive pattern matching with the 'match' keyword

Introduction & Core Concept

Rust enums are algebraic data types that can hold different types and amounts of data in each variant. The Option enum represents either Some(value) or None.
WHY DOES THIS MATTER IN THE REAL WORLD?

Tony Hoare called null his 'billion-dollar mistake'. Option<T> forces you to explicitly handle the None case at compile time.

Option Pattern Matching

rust
rust
1
2
3
4
5
6
7
8
9
10
fn divide(numerator: f64, denominator: f64) -> Option<f64> {
if denominator == 0.0 { None } else { Some(numerator / denominator) }
}
fn main() {
match divide(10.0, 2.0) {
Some(result) => println!("Quotient: {}", result),
None => println!("Cannot divide by zero!"),
}
}

Line-by-Line Technical Breakdown

1Use 'if let Some(val) = opt' when you only care about matching a single variant.

Try It Yourself (Interactive Editor)

Modify the code in real-time and click Run to test live browser output and console logs.

Intelligent Code Runner & Live Sandbox[RUST]
RUST SOURCE EDITOR
Interactive Live Code

Industry Best Practices & Professional Standards

  • Use Option<T> for any value that might be absent.

Lesson Summary & Core Takeaways

  • Enums and Option eliminate null pointer crashes entirely.