Rust Tutorial: Enums and Option
Define enums with data, use Option to represent nullable values, and avoid null pointer bugs.
Enums carry data
Rust enums are much more powerful than in most languages — each variant can carry different data.
`Option<T>` is the built-in enum that replaces null. No more null pointer exceptions.
What you'll learn in this Rust enums and option tutorial
This interactive Rust tutorial has 8 hands-on exercises. Estimated time: 20 minutes.
- Basic enum — Define an enum with variants. Use `::` to construct a variant.
- Enums with data — Enum variants can carry data of different types:
- Option<T> — no null — `Option<T>` is either `Some(value)` or `None`. It replaces null.
- Unwrapping Option — `unwrap()` extracts the value from `Some`, panicking on `None`.
- if let with Option — `if let Some(x) = option` destructures Some without needing a full match.
- unwrap_or and unwrap_or_else — Provide a fallback instead of panicking:
- Option methods: map and and_then — `map` transforms the inner value. `and_then` chains Options.
- Nested Option with ? — In functions returning Option, use `?` to propagate None automatically.
Rust Enums and Option concepts covered
- Enums carry data