Skip to main content

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

basic_enum.mux
Loading...

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

creating_enums.mux
Loading...

Pattern Matching with Enums

Use match to handle different enum variants:

pattern_matching_enums.mux
Loading...

Ignoring Associated Data

Use _ to ignore data you don't need:

ignoring_enum_data.mux
Loading...

Pattern Matching with Guards

Add conditional logic with guards:

enum_guards.mux
Loading...

Generic Enums

Enums can be generic over type parameters:

enum_generics.mux
Loading...

Common Enum Patterns

optional Values

optional_values.mux
Loading...

result Types for Error Handling

result_types.mux
Loading...

See Error Handling for more details on result and optional.

State Machines

state_machines.mux
Loading...

Nested Enums

nested_enums.mux
Loading...

Enums in Collections

enums_in_collections.mux
Loading...

Exhaustiveness Checking

Mux enforces exhaustive pattern matching - all variants must be covered:

exhaustiveness_checking.mux
Loading...

Best Practices

  1. Use enums for mutually exclusive states - Better than multiple booleans
  2. Match exhaustively - Don't overuse wildcard patterns
  3. Use guards for additional logic - Cleaner than nested if statements
  4. Ignore unused data with _ - Makes intent explicit
  5. Prefer result over exceptions - Explicit error handling
  6. Prefer optional over null - No null pointer errors
  7. Use generic enums for reusable patterns - Option<T>, result<T, E>

See Also