Enums / Tagged Unions
Enums in Mux are tagged unions (also called algebraic data types or sum types) that can hold different variants with associated data.
Basic Enum Definition
Key Points:
- Each variant is a case of the enum
- Variants can carry associated data (or none)
- Variants are constructed using
.new()syntax
Creating Enum Instances
Pattern Matching with Enums
Use match to handle different enum variants:
Ignoring Associated Data
Use _ to ignore data you don't need:
Pattern Matching with Guards
Add conditional logic with guards:
Generic Enums
Enums can be generic over type parameters:
Common Enum Patterns
optional Values
result Types for Error Handling
See Error Handling for more details on result and optional.
State Machines
Nested Enums
Enums in Collections
Exhaustiveness Checking
Mux enforces exhaustive pattern matching - all variants must be covered:
Best Practices
- Use enums for mutually exclusive states - Better than multiple booleans
- Match exhaustively - Don't overuse wildcard patterns
- Use guards for additional logic - Cleaner than nested if statements
- Ignore unused data with
_- Makes intent explicit - Prefer result over exceptions - Explicit error handling
- Prefer optional over null - No null pointer errors
- Use generic enums for reusable patterns - Option<T>, result<T, E>
See Also
- Error Handling - result and optional types
- Control Flow - Pattern matching with match
- Generics - Generic enums
- Collections - Enums in lists and maps