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:

  • match arms
  • if let expressions
  • while let loops
  • Function parameters
  • let statements

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!