Files
docs-rust/ch19/ch19-00-patterns.html
2026-06-22 21:27:36 +05:30

36 lines
1.7 KiB
HTML
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Patterns and Matching</title>
</head>
<body>
<h1 id="patterns-and-matching"><a class="header" href="#patterns-and-matching">Patterns and Matching</a></h1>
<p>Patterns are a special syntax in Rust for matching against the structure of
types, both complex and simple. Using patterns in conjunction with <code>match</code>
expressions and other constructs gives you more control over a programs
control flow. A pattern consists of some combination of the following:</p>
<ul>
<li>Literals</li>
<li>Destructured arrays, enums, structs, or tuples</li>
<li>Variables</li>
<li>Wildcards</li>
<li>Placeholders</li>
</ul>
<p>Some example patterns include <code>x</code>, <code>(a, 3)</code>, and <code>Some(Color::Red)</code>. 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.</p>
<p>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 <code>match</code> expressions in
Chapter 6 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
doesnt, the code associated with the pattern wont run.</p>
<p>This chapter is a reference on all things related to patterns. Well cover the
valid places to use patterns, the difference between refutable and irrefutable
patterns, and the different kinds of pattern syntax that you might see. By the
end of the chapter, youll know how to use patterns to express many concepts in
a clear way.</p>
</body>
</html>