Other Places to Use Patterns
In addition to match expressions, the pattern can also be used in variable definitions (the pattern is on the left of the equal sign) and for in expressions (the pattern is between the for keyword and the in keyword).
However, not all patterns can be used in variable definitions and for in expressions. Only the irrefutable pattern can be used in these two contexts. Therefore, only the wildcard pattern, binding pattern, irrefutable tuple pattern, and irrefutable enum pattern are allowed.
-
The following is an example of using the wildcard pattern in variable definitions and
for inexpressions:main() { let _ = 100 for (_ in 1..5) { println("0") } }In the preceding example, the wildcard pattern is used in the variable definition, indicating that an unnamed variable is defined (the variable cannot be accessed later). The wildcard pattern is used in the
for inexpression, indicating that the elements in1..5are not bound to any variable (the element values in1..5cannot be accessed in the loop body). The result is as follows:0 0 0 0 -
The following is an example of using the binding pattern in variable definitions and
for inexpressions:main() { let x = 100 println("x = ${x}") for (i in 1..5) { println(i) } }In the preceding example, both
xin the variable definition andiin thefor inexpression are binding patterns. The result is as follows:x = 100 1 2 3 4 -
The following is an example of using the
irrefutabletuple pattern in variable definitions and for in expressions:main() { let (x, y) = (100, 200) println("x = ${x}") println("y = ${y}") for ((i, j) in [(1, 2), (3, 4), (5, 6)]) { println("Sum = ${i + j}") } }In the preceding example, the tuple pattern is used in the variable definition, indicating that
(100, 200)is deconstructed and bound toxandyrespectively. The effect is equivalent to defining two variablesxandy. Thefor inexpression uses a tuple pattern to extract the tuple elements from[(1, 2), (3, 4), (5, 6)], destructing them and binding the values toiandjrespectively, and the loop body outputs the value ofi + j. The result is as follows:x = 100 y = 200 Sum = 3 Sum = 7 Sum = 11 -
The following is an example of using the
irrefutableenum pattern in variable definitions and for in expressions:enum RedColor { Red(Int64) } main() { let Red(red) = Red(0) println("red = ${red}") for (Red(r) in [Red(10), Red(20), Red(30)]) { println("r = ${r}") } }In the preceding example, the enum pattern is used in the variable definition, indicating that
Red(0)is deconstructed and the parameter value (that is,0) of the constructor is bound tored. The enum pattern is used in thefor inexpression, indicating that the elements in[Red(10), Red(20), Red(30)]are obtained in sequence, the constructor parameter values are deconstructed and bound tor, and the value ofris output in the loop body. The result is as follows:red = 0 r = 10 r = 20 r = 30