Rust Enums
🦀 Rust Enums
They are extremely powerful and are a core reason why Rust code is safe, expressive, and clean.
1. What Is an Enum?
An enum defines a type with a fixed set of possible values.
Here, a value of Direction can be only one of these four.
2. Creating and Using Enum Values
Enums are often used with match.
3. Enums with match (Very Important)
✔ match must be exhaustive
✔ Compiler ensures all cases are handled
4. Enums with Data (Power Feature 🔥)
Each enum variant can store data.
Usage:
5. Matching Enums with Data
✔ Destructuring happens naturally
✔ Very readable code
6. Option<T> – No null in Rust
Rust does not have null.
Instead, it uses Option<T>.
Example:
✔ Prevents null pointer errors
✔ Compiler forces you to handle missing values
7. Result<T, E> – Error Handling
Another important enum.
Example:
Usage:
8. Enum Methods (impl)
Enums can have methods too.
9. if let – Shorter Matching
When you care about only one case.
✔ Cleaner than match for simple cases
10. Enums vs Structs
| Feature | Enum | Struct |
|---|---|---|
| Multiple variants | ✔ | ❌ |
| Different shapes | ✔ | ❌ |
| Use with match | ✔ | ❌ |
| Fixed fields | ❌ | ✔ |
👉 Use enum when a value can be one of many forms.
❌ Common Mistakes
-
Forgetting to handle all enum cases
-
Overusing
unwrap() -
Using
structwhen enum fits better -
Not leveraging enums with data
🧠 Key Takeaways
-
Enums define multiple possible states
-
Variants can store different data
-
match+ enum = super power -
OptionandResultare core enums -
Compiler enforces safety
