]>
Commit | Line | Data |
---|---|---|
abe05a73 | 1 | # Patterns and Matching |
cc61c64b | 2 | |
abe05a73 XL |
3 | Patterns are a special syntax in Rust for matching against the structure of |
4 | types, both complex and simple. Using patterns in conjunction with `match` | |
5 | expressions and other constructs gives you more control over the control flow | |
6 | of a program. A pattern is made up of some combination of: | |
cc61c64b | 7 | |
abe05a73 XL |
8 | - literals |
9 | - destructured arrays, enums, structs, or tuples | |
10 | - variables | |
11 | - wildcards | |
12 | - placeholders | |
13 | ||
14 | These pieces describe the shape of the data we’re working with, which we then | |
15 | match against values to determine whether our program has the correct data to | |
16 | continue running a particular bit of code. | |
17 | ||
18 | <!-- I think we need a concise description of what we use patterns for here, | |
19 | what they provide the programmer. Hopefully you can see what I've trying to do, | |
20 | above! But I think you'll agree it's not quite right, can you have a whack, try | |
21 | to give the reader that explanation? --> | |
22 | <!-- We tweaked the wording a bit, how's this? /Carol --> | |
23 | ||
24 | To use a pattern we compare it to some value. If the pattern matches our value, | |
25 | we use the value parts in our code. Recall our `match` expressions from Chapter | |
26 | 6 that used patterns like a coin sorting machine. If the value fits the shape | |
27 | of the pattern, we can use the named pieces. If it doesn’t, the code associated | |
28 | with the pattern won’t run. | |
cc61c64b | 29 | |
3b2f2976 | 30 | This chapter is a reference on all things related to patterns. We’ll cover the |
cc61c64b XL |
31 | valid places to use patterns, the difference between *refutable* and |
32 | *irrefutable* patterns, and the different kinds of pattern syntax that you | |
abe05a73 XL |
33 | might see. By the end, you’ll see how to use patterns to create powerful and |
34 | clear code. |