|
| 1 | +--- |
| 2 | +minutes: 5 |
| 3 | +--- |
| 4 | + |
| 5 | +# Irrefutable Patterns |
| 6 | + |
| 7 | +In day 1 we briefly saw how patterns can be used to _destructure_ compound |
| 8 | +values. Let's review that and talk about a few other things patterns can |
| 9 | +express: |
| 10 | + |
| 11 | +```rust,editable |
| 12 | +fn takes_tuple(tuple: (char, i32, bool)) { |
| 13 | + let a = tuple.0; |
| 14 | + let b = tuple.1; |
| 15 | + let c = tuple.2; |
| 16 | +
|
| 17 | + // This does the same thing as above. |
| 18 | + let (a, b, c) = tuple; |
| 19 | +
|
| 20 | + // Ignore the first element, only bind the second and third. |
| 21 | + let (_, b, c) = tuple; |
| 22 | +
|
| 23 | + // Ignore everything but the last element. |
| 24 | + let (.., c) = tuple; |
| 25 | +} |
| 26 | +
|
| 27 | +fn main() { |
| 28 | + takes_tuple(('a', 777, true)); |
| 29 | +} |
| 30 | +``` |
| 31 | + |
| 32 | +<details> |
| 33 | + |
| 34 | +- All of the demonstrated patterns are _irrefutable_, meaning that they will |
| 35 | + always match the value on the right hand side. |
| 36 | + |
| 37 | +- Variable names are patterns that always match and which bind the matched value |
| 38 | + into a new variable with that name. |
| 39 | + |
| 40 | +- `_` is a pattern that always matches any value, discarding the matched value. |
| 41 | + |
| 42 | +- `..` alows you to ignore multiple values at once. |
| 43 | + |
| 44 | +## More to Explore |
| 45 | + |
| 46 | +- You can also demonstrate more advanced usages of `..`, such as ignoring the |
| 47 | + middle elements of a tuple. |
| 48 | + |
| 49 | + ```rust |
| 50 | + fn takes_tuple(tuple: (char, i32, bool, u8)) { |
| 51 | + let (first, .., last) = tuple; |
| 52 | + } |
| 53 | + ``` |
| 54 | + |
| 55 | +- All of these patterns work with arrays as well: |
| 56 | + |
| 57 | + ```rust |
| 58 | + fn takes_array(array: [u8; 5]) { |
| 59 | + let [first, .., last] = array; |
| 60 | + } |
| 61 | + ``` |
| 62 | + |
| 63 | +</details> |
0 commit comments