Versions/v1.1.0/English

Other Usage Scenarios of Patterns

Sections1
On This Page1
API Symbols0

Other Usage Scenarios of Patterns

Patterns can be used not only in match expressions but also in variable definitions and for in expressions. For example, the left side of an equals sign is a pattern, and the part between the for keyword and the in keyword is also a pattern. Additionally, conditions in if expressions and while expressions can utilize patterns. For specific examples, refer to the "Conditions Involving let-pattern" section.

However, not all patterns can be used in variable definitions and for in expressions. Only irrefutable patterns are permitted in these contexts. Therefore, only wildcard patterns, binding patterns, irrefutable tuple patterns, and irrefutable enum patterns are allowed.

1. Examples of using wildcard patterns in variable definitions and for in expressions:

In the above example, a wildcard pattern is used in the variable definition, indicating the creation of a nameless variable (which consequently cannot be accessed later). The for in expression uses a wildcard pattern, meaning elements from 1..5 won't be bound to any variable (thus their values cannot be accessed within the loop body). Compiling and executing this code yields:

2. Examples of using binding patterns in variable definitions and for in expressions:

Here, x in the variable definition and i in the for in expression are both binding patterns. Compiling and executing this code yields:

3. Examples of using irrefutable tuple patterns in variable definitions and for in expressions:

In this example, a tuple pattern is used in the variable definition to destructure (100, 200) and bind its components to x and y, effectively defining two variables. The for in expression employs a tuple pattern to sequentially extract tuple-type elements from [(1, 2), (3, 4), (5, 6)], destructure them, and bind their components to i and j, then output their sum in the loop body. Compiling and executing this code yields:

4. Examples of using irrefutable enum patterns in variable definitions and for in expressions:

Here, an enum pattern is used in the variable definition to destructure Red(0) and bind its constructor parameter (i.e., 0) to red. The for in expression uses an enum pattern to sequentially extract elements from [Red(10), Red(20), Red(30)], destructure them, and bind their constructor parameters to r, then output r in the loop body. Compiling and executing this code yields: