Control Flow
Mux provides familiar control flow constructs with some unique features like pattern matching with guards.
If / Else
Standard if-else branching with curly braces:
If as an Expression
In Mux, if can be used as an expression that returns a value:
For Loops
Mux uses range-based for loops only (no C-style for (int i = 0; i < n; i++)):
Ignoring Loop Variables
Use _ when you don't need the loop variable:
Iterating Collections
While Loops
Standard while loops with boolean conditions:
Break and Continue
Control loop execution:
Match Statements
Pattern matching with guards and destructuring:
Basic Matching
This is equivalent to:
Matching optional
Matching result
Pattern Matching with Guards
Guards add conditional logic to patterns:
Ignoring Values in Patterns
Use _ to ignore parts of patterns you don't need:
Matching Enums
Wildcard Pattern
The _ pattern matches anything:
Exhaustive Matching
Mux requires that all possible cases are handled in a match statement. If you miss a case, the compiler will give an error:
Match as Switch Statement
Match statements can be used as switch statements for any type, not just enums:
Variable Binding in Switch Patterns
Capture matched values in variables:
Constants in Switch Patterns
Use constants as match patterns:
List Literal Matching
Match on list structure:
Switch with Guards
Add conditions to switch cases:
Return Statement
Exit a function early:
Best Practices
- Use
usefor sequential propagation - It extracts the success value and returns the enclosing function'serr/nonewithout nested matches - Use inspection methods for local handling - Check
is_ok()/is_err()oris_some()/is_none()before callingvalue()orerror() - Prefer pattern matching with guards - Cleaner than nested if statements
- Use
_for unused values - Makes intent explicit - Early returns for error conditions - Reduces nesting
- Use
range()for numeric loops - Idiomatic Mux - Break and continue judiciously - Can make code harder to follow if overused
See Also
- Error Handling - Using
use, inspection, and match - Enums - Pattern matching with tagged unions
- Functions - Return statements and early exits
- Variables - Type inference with
auto