]> git.proxmox.com Git - rustc.git/blob - src/doc/book/second-edition/src/ch18-00-patterns.md
New upstream version 1.23.0+dfsg1
[rustc.git] / src / doc / book / second-edition / src / ch18-00-patterns.md
1 # Patterns and Matching
2
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:
7
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.
29
30 This chapter is a reference on all things related to patterns. We’ll cover the
31 valid places to use patterns, the difference between *refutable* and
32 *irrefutable* patterns, and the different kinds of pattern syntax that you
33 might see. By the end, you’ll see how to use patterns to create powerful and
34 clear code.