Patterns and Matching
Patterns are a special syntax in Oxide for matching against the structure of types, both complex and simple. Using patterns in combination with match expressions and other constructs gives you more control over your program's control flow. A pattern consists of some combination of the following:
- Literal values
- Destructured arrays, enums, structs, or tuples
- Variables
- Wildcards
- Placeholders
Some example patterns include x, (a, b), and Point { x, y }.
What You'll Learn
In this chapter, we cover:
All the Places Patterns Can Be Used
Patterns appear in several places in Oxide code:
matcharmsif letexpressionswhile letloops- Function parameters
letstatements
Refutability: Whether a Pattern Might Fail to Match
Patterns come in two forms:
- Refutable patterns: patterns that might fail to match for some values
- Irrefutable patterns: patterns that will always match for any value passed
Understanding this distinction is crucial for writing correct Oxide code.
Pattern Syntax
We'll explore all the ways you can construct patterns to match values:
- Literal patterns
- Named variables
- Multiple patterns with
| - Destructuring structs, enums, and tuples
- Wildcard patterns with
else - Range patterns
- Binding patterns with guards
Pattern matching is one of the most powerful features in Oxide, and mastering it will help you write cleaner, more expressive code that fully leverages the compiler's ability to ensure correctness.
Let's dive into how patterns work!