Skip to content

Commit 7407e54

Browse files
committed
Add slide covering irrefutable patterns
1 parent 347de61 commit 7407e54

File tree

2 files changed

+64
-0
lines changed

2 files changed

+64
-0
lines changed

src/SUMMARY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,6 +77,7 @@
7777

7878
- [Welcome](welcome-day-2.md)
7979
- [Pattern Matching](pattern-matching.md)
80+
- [Irrefutable Patterns](pattern-matching/infallible.md)
8081
- [Matching Values](pattern-matching/match.md)
8182
- [Destructuring Structs](pattern-matching/destructuring-structs.md)
8283
- [Destructuring Enums](pattern-matching/destructuring-enums.md)

src/pattern-matching/infallible.md

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
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

Comments
 (0)