mirror of
https://github.com/darkicewolf50/RustBrock.git
synced 2025-06-15 13:04:18 -06:00
34 lines
1.4 KiB
Markdown
34 lines
1.4 KiB
Markdown
# Patterns and Matching
|
|
*Patterns* are a special syntax in Rust for matching against the structure of types, both complex and simple.
|
|
|
|
Using patterns in conjunction with `match` expressions and other constructs give you more control over a program's flow.
|
|
|
|
A pattern consists of some combination of the following:
|
|
- Literals
|
|
- Destructured arrays, enums, structs, or tuples
|
|
- Variables
|
|
- Wildcards
|
|
- Placeholders
|
|
Some examples include `x`, `(a, 3)` and `Some(Color::Red)`.
|
|
|
|
In the contexts in which patterns are valid, these components describe the shape of data.
|
|
|
|
Our program then matches values against the patterns to determine whether it has the correct shape of data to continue running a particular piece of code.
|
|
|
|
In order to use a pattern, we compare it to some value.
|
|
|
|
If the pattern matches the value, we use the value parts in our code.
|
|
|
|
Recall the `match` expression that used patterns, such as the coin-sorting machine example.
|
|
|
|
If the value fits the shape of the pattern, we can use the named pieces.
|
|
|
|
If it doesn't, the code associated with the pattern won't run.
|
|
|
|
This chapter is intended to be a reference on all things related to patterns.
|
|
|
|
We will cover:
|
|
- Valid places to use patterns [Section Link Here]()
|
|
- Difference between refutable and irrefutable patterns
|
|
- different kinds of pattern syntax
|
|
By the end you will know how to use patterns to express many concepts in a clear way. |