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