feat: added cleanscript
This commit is contained in:
371
ch06/ch06-02-match.html
Normal file
371
ch06/ch06-02-match.html
Normal file
@@ -0,0 +1,371 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>The match Control Flow Construct</title>
|
||||
</head>
|
||||
<body>
|
||||
<!-- Old headings. Do not remove or links may break. -->
|
||||
<p><a id="the-match-control-flow-operator"></a></p>
|
||||
<h2 id="the-match-control-flow-construct"><a class="header" href="#the-match-control-flow-construct">The <code>match</code> Control Flow Construct</a></h2>
|
||||
<p>Rust has an extremely powerful control flow construct called <code>match</code> that
|
||||
allows you to compare a value against a series of patterns and then execute
|
||||
code based on which pattern matches. Patterns can be made up of literal values,
|
||||
variable names, wildcards, and many other things; <a href="../ch19/ch19-00-patterns.html">Chapter
|
||||
19</a><!-- ignore --> covers all the different kinds of patterns
|
||||
and what they do. The power of <code>match</code> comes from the expressiveness of the
|
||||
patterns and the fact that the compiler confirms that all possible cases are
|
||||
handled.</p>
|
||||
<p>Think of a <code>match</code> expression as being like a coin-sorting machine: Coins slide
|
||||
down a track with variously sized holes along it, and each coin falls through
|
||||
the first hole it encounters that it fits into. In the same way, values go
|
||||
through each pattern in a <code>match</code>, and at the first pattern the value “fits,”
|
||||
the value falls into the associated code block to be used during execution.</p>
|
||||
<p>Speaking of coins, let’s use them as an example using <code>match</code>! We can write a
|
||||
function that takes an unknown US coin and, in a similar way as the counting
|
||||
machine, determines which coin it is and returns its value in cents, as shown
|
||||
in Listing 6-3.</p>
|
||||
<figure class="listing" id="listing-6-3">
|
||||
<pre class="playground"><code class="language-rust edition2024">enum Coin {
|
||||
Penny,
|
||||
Nickel,
|
||||
Dime,
|
||||
Quarter,
|
||||
}
|
||||
|
||||
fn value_in_cents(coin: Coin) -> u8 {
|
||||
match coin {
|
||||
Coin::Penny => 1,
|
||||
Coin::Nickel => 5,
|
||||
Coin::Dime => 10,
|
||||
Coin::Quarter => 25,
|
||||
}
|
||||
}
|
||||
<span class="boring">
|
||||
</span><span class="boring">fn main() {}</span></code></pre>
|
||||
<figcaption><a href="#listing-6-3">Listing 6-3</a>: An enum and a <code>match</code> expression that has the variants of the enum as its patterns</figcaption>
|
||||
</figure>
|
||||
<p>Let’s break down the <code>match</code> in the <code>value_in_cents</code> function. First, we list
|
||||
the <code>match</code> keyword followed by an expression, which in this case is the value
|
||||
<code>coin</code>. This seems very similar to a conditional expression used with <code>if</code>, but
|
||||
there’s a big difference: With <code>if</code>, the condition needs to evaluate to a
|
||||
Boolean value, but here it can be any type. The type of <code>coin</code> in this example
|
||||
is the <code>Coin</code> enum that we defined on the first line.</p>
|
||||
<p>Next are the <code>match</code> arms. An arm has two parts: a pattern and some code. The
|
||||
first arm here has a pattern that is the value <code>Coin::Penny</code> and then the <code>=></code>
|
||||
operator that separates the pattern and the code to run. The code in this case
|
||||
is just the value <code>1</code>. Each arm is separated from the next with a comma.</p>
|
||||
<p>When the <code>match</code> expression executes, it compares the resultant value against
|
||||
the pattern of each arm, in order. If a pattern matches the value, the code
|
||||
associated with that pattern is executed. If that pattern doesn’t match the
|
||||
value, execution continues to the next arm, much as in a coin-sorting machine.
|
||||
We can have as many arms as we need: In Listing 6-3, our <code>match</code> has four arms.</p>
|
||||
<p>The code associated with each arm is an expression, and the resultant value of
|
||||
the expression in the matching arm is the value that gets returned for the
|
||||
entire <code>match</code> expression.</p>
|
||||
<p>We don’t typically use curly brackets if the match arm code is short, as it is
|
||||
in Listing 6-3 where each arm just returns a value. If you want to run multiple
|
||||
lines of code in a match arm, you must use curly brackets, and the comma
|
||||
following the arm is then optional. For example, the following code prints
|
||||
“Lucky penny!” every time the method is called with a <code>Coin::Penny</code>, but it
|
||||
still returns the last value of the block, <code>1</code>:</p>
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">enum Coin {
|
||||
</span><span class="boring"> Penny,
|
||||
</span><span class="boring"> Nickel,
|
||||
</span><span class="boring"> Dime,
|
||||
</span><span class="boring"> Quarter,
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span>fn value_in_cents(coin: Coin) -> u8 {
|
||||
match coin {
|
||||
Coin::Penny => {
|
||||
println!("Lucky penny!");
|
||||
1
|
||||
}
|
||||
Coin::Nickel => 5,
|
||||
Coin::Dime => 10,
|
||||
Coin::Quarter => 25,
|
||||
}
|
||||
}
|
||||
<span class="boring">
|
||||
</span><span class="boring">fn main() {}</span></code></pre>
|
||||
<h3 id="patterns-that-bind-to-values"><a class="header" href="#patterns-that-bind-to-values">Patterns That Bind to Values</a></h3>
|
||||
<p>Another useful feature of match arms is that they can bind to the parts of the
|
||||
values that match the pattern. This is how we can extract values out of enum
|
||||
variants.</p>
|
||||
<p>As an example, let’s change one of our enum variants to hold data inside it.
|
||||
From 1999 through 2008, the United States minted quarters with different
|
||||
designs for each of the 50 states on one side. No other coins got state
|
||||
designs, so only quarters have this extra value. We can add this information to
|
||||
our <code>enum</code> by changing the <code>Quarter</code> variant to include a <code>UsState</code> value
|
||||
stored inside it, which we’ve done in Listing 6-4.</p>
|
||||
<figure class="listing" id="listing-6-4">
|
||||
<pre class="playground"><code class="language-rust edition2024">#[derive(Debug)] // so we can inspect the state in a minute
|
||||
enum UsState {
|
||||
Alabama,
|
||||
Alaska,
|
||||
// --snip--
|
||||
}
|
||||
|
||||
enum Coin {
|
||||
Penny,
|
||||
Nickel,
|
||||
Dime,
|
||||
Quarter(UsState),
|
||||
}
|
||||
<span class="boring">
|
||||
</span><span class="boring">fn main() {}</span></code></pre>
|
||||
<figcaption><a href="#listing-6-4">Listing 6-4</a>: A <code>Coin</code> enum in which the <code>Quarter</code> variant also holds a <code>UsState</code> value</figcaption>
|
||||
</figure>
|
||||
<p>Let’s imagine that a friend is trying to collect all 50 state quarters. While
|
||||
we sort our loose change by coin type, we’ll also call out the name of the
|
||||
state associated with each quarter so that if it’s one our friend doesn’t have,
|
||||
they can add it to their collection.</p>
|
||||
<p>In the match expression for this code, we add a variable called <code>state</code> to the
|
||||
pattern that matches values of the variant <code>Coin::Quarter</code>. When a
|
||||
<code>Coin::Quarter</code> matches, the <code>state</code> variable will bind to the value of that
|
||||
quarter’s state. Then, we can use <code>state</code> in the code for that arm, like so:</p>
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">#[derive(Debug)]
|
||||
</span><span class="boring">enum UsState {
|
||||
</span><span class="boring"> Alabama,
|
||||
</span><span class="boring"> Alaska,
|
||||
</span><span class="boring"> // --snip--
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span><span class="boring">enum Coin {
|
||||
</span><span class="boring"> Penny,
|
||||
</span><span class="boring"> Nickel,
|
||||
</span><span class="boring"> Dime,
|
||||
</span><span class="boring"> Quarter(UsState),
|
||||
</span><span class="boring">}
|
||||
</span><span class="boring">
|
||||
</span>fn value_in_cents(coin: Coin) -> u8 {
|
||||
match coin {
|
||||
Coin::Penny => 1,
|
||||
Coin::Nickel => 5,
|
||||
Coin::Dime => 10,
|
||||
Coin::Quarter(state) => {
|
||||
println!("State quarter from {state:?}!");
|
||||
25
|
||||
}
|
||||
}
|
||||
}
|
||||
<span class="boring">
|
||||
</span><span class="boring">fn main() {
|
||||
</span><span class="boring"> value_in_cents(Coin::Quarter(UsState::Alaska));
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<p>If we were to call <code>value_in_cents(Coin::Quarter(UsState::Alaska))</code>, <code>coin</code>
|
||||
would be <code>Coin::Quarter(UsState::Alaska)</code>. When we compare that value with each
|
||||
of the match arms, none of them match until we reach <code>Coin::Quarter(state)</code>. At
|
||||
that point, the binding for <code>state</code> will be the value <code>UsState::Alaska</code>. We can
|
||||
then use that binding in the <code>println!</code> expression, thus getting the inner
|
||||
state value out of the <code>Coin</code> enum variant for <code>Quarter</code>.</p>
|
||||
<!-- Old headings. Do not remove or links may break. -->
|
||||
<p><a id="matching-with-optiont"></a></p>
|
||||
<h3 id="the-optiont-match-pattern"><a class="header" href="#the-optiont-match-pattern">The <code>Option<T></code> <code>match</code> Pattern</a></h3>
|
||||
<p>In the previous section, we wanted to get the inner <code>T</code> value out of the <code>Some</code>
|
||||
case when using <code>Option<T></code>; we can also handle <code>Option<T></code> using <code>match</code>, as
|
||||
we did with the <code>Coin</code> enum! Instead of comparing coins, we’ll compare the
|
||||
variants of <code>Option<T></code>, but the way the <code>match</code> expression works remains the
|
||||
same.</p>
|
||||
<p>Let’s say we want to write a function that takes an <code>Option<i32></code> and, if
|
||||
there’s a value inside, adds 1 to that value. If there isn’t a value inside,
|
||||
the function should return the <code>None</code> value and not attempt to perform any
|
||||
operations.</p>
|
||||
<p>This function is very easy to write, thanks to <code>match</code>, and will look like
|
||||
Listing 6-5.</p>
|
||||
<figure class="listing" id="listing-6-5">
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||||
</span> fn plus_one(x: Option<i32>) -> Option<i32> {
|
||||
match x {
|
||||
None => None,
|
||||
Some(i) => Some(i + 1),
|
||||
}
|
||||
}
|
||||
|
||||
let five = Some(5);
|
||||
let six = plus_one(five);
|
||||
let none = plus_one(None);
|
||||
<span class="boring">}</span></code></pre>
|
||||
<figcaption><a href="#listing-6-5">Listing 6-5</a>: A function that uses a <code>match</code> expression on an <code>Option<i32></code></figcaption>
|
||||
</figure>
|
||||
<p>Let’s examine the first execution of <code>plus_one</code> in more detail. When we call
|
||||
<code>plus_one(five)</code>, the variable <code>x</code> in the body of <code>plus_one</code> will have the
|
||||
value <code>Some(5)</code>. We then compare that against each match arm:</p>
|
||||
<pre><code class="language-rust ignore"><span class="boring">fn main() {
|
||||
</span><span class="boring"> fn plus_one(x: Option<i32>) -> Option<i32> {
|
||||
</span><span class="boring"> match x {
|
||||
</span> None => None,
|
||||
<span class="boring"> Some(i) => Some(i + 1),
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> let five = Some(5);
|
||||
</span><span class="boring"> let six = plus_one(five);
|
||||
</span><span class="boring"> let none = plus_one(None);
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<p>The <code>Some(5)</code> value doesn’t match the pattern <code>None</code>, so we continue to the
|
||||
next arm:</p>
|
||||
<pre><code class="language-rust ignore"><span class="boring">fn main() {
|
||||
</span><span class="boring"> fn plus_one(x: Option<i32>) -> Option<i32> {
|
||||
</span><span class="boring"> match x {
|
||||
</span><span class="boring"> None => None,
|
||||
</span> Some(i) => Some(i + 1),
|
||||
<span class="boring"> }
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> let five = Some(5);
|
||||
</span><span class="boring"> let six = plus_one(five);
|
||||
</span><span class="boring"> let none = plus_one(None);
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<p>Does <code>Some(5)</code> match <code>Some(i)</code>? It does! We have the same variant. The <code>i</code>
|
||||
binds to the value contained in <code>Some</code>, so <code>i</code> takes the value <code>5</code>. The code in
|
||||
the match arm is then executed, so we add 1 to the value of <code>i</code> and create a
|
||||
new <code>Some</code> value with our total <code>6</code> inside.</p>
|
||||
<p>Now let’s consider the second call of <code>plus_one</code> in Listing 6-5, where <code>x</code> is
|
||||
<code>None</code>. We enter the <code>match</code> and compare to the first arm:</p>
|
||||
<pre><code class="language-rust ignore"><span class="boring">fn main() {
|
||||
</span><span class="boring"> fn plus_one(x: Option<i32>) -> Option<i32> {
|
||||
</span><span class="boring"> match x {
|
||||
</span> None => None,
|
||||
<span class="boring"> Some(i) => Some(i + 1),
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring"> }
|
||||
</span><span class="boring">
|
||||
</span><span class="boring"> let five = Some(5);
|
||||
</span><span class="boring"> let six = plus_one(five);
|
||||
</span><span class="boring"> let none = plus_one(None);
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<p>It matches! There’s no value to add to, so the program stops and returns the
|
||||
<code>None</code> value on the right side of <code>=></code>. Because the first arm matched, no other
|
||||
arms are compared.</p>
|
||||
<p>Combining <code>match</code> and enums is useful in many situations. You’ll see this
|
||||
pattern a lot in Rust code: <code>match</code> against an enum, bind a variable to the
|
||||
data inside, and then execute code based on it. It’s a bit tricky at first, but
|
||||
once you get used to it, you’ll wish you had it in all languages. It’s
|
||||
consistently a user favorite.</p>
|
||||
<h3 id="matches-are-exhaustive"><a class="header" href="#matches-are-exhaustive">Matches Are Exhaustive</a></h3>
|
||||
<p>There’s one other aspect of <code>match</code> we need to discuss: The arms’ patterns must
|
||||
cover all possibilities. Consider this version of our <code>plus_one</code> function,
|
||||
which has a bug and won’t compile:</p>
|
||||
<pre><code class="language-rust ignore does_not_compile"><span class="boring">fn main() {
|
||||
</span> fn plus_one(x: Option<i32>) -> Option<i32> {
|
||||
match x {
|
||||
Some(i) => Some(i + 1),
|
||||
}
|
||||
}
|
||||
<span class="boring">
|
||||
</span><span class="boring"> let five = Some(5);
|
||||
</span><span class="boring"> let six = plus_one(five);
|
||||
</span><span class="boring"> let none = plus_one(None);
|
||||
</span><span class="boring">}</span></code></pre>
|
||||
<p>We didn’t handle the <code>None</code> case, so this code will cause a bug. Luckily, it’s
|
||||
a bug Rust knows how to catch. If we try to compile this code, we’ll get this
|
||||
error:</p>
|
||||
<pre><code class="language-console">$ cargo run
|
||||
Compiling enums v0.1.0 (file:///projects/enums)
|
||||
error[E0004]: non-exhaustive patterns: `None` not covered
|
||||
--> src/main.rs:3:15
|
||||
|
|
||||
3 | match x {
|
||||
| ^ pattern `None` not covered
|
||||
|
|
||||
note: `Option<i32>` defined here
|
||||
--> /rustc/1159e78c4747b02ef996e55082b704c09b970588/library/core/src/option.rs:593:1
|
||||
::: /rustc/1159e78c4747b02ef996e55082b704c09b970588/library/core/src/option.rs:597:5
|
||||
|
|
||||
= note: not covered
|
||||
= note: the matched value is of type `Option<i32>`
|
||||
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
||||
|
|
||||
4 ~ Some(i) => Some(i + 1),
|
||||
5 ~ None => todo!(),
|
||||
|
|
||||
|
||||
For more information about this error, try `rustc --explain E0004`.
|
||||
error: could not compile `enums` (bin "enums") due to 1 previous error
|
||||
</code></pre>
|
||||
<p>Rust knows that we didn’t cover every possible case and even knows which
|
||||
pattern we forgot! Matches in Rust are <em>exhaustive</em>: We must exhaust every last
|
||||
possibility in order for the code to be valid. Especially in the case of
|
||||
<code>Option<T></code>, when Rust prevents us from forgetting to explicitly handle the
|
||||
<code>None</code> case, it protects us from assuming that we have a value when we might
|
||||
have null, thus making the billion-dollar mistake discussed earlier impossible.</p>
|
||||
<h3 id="catch-all-patterns-and-the-_-placeholder"><a class="header" href="#catch-all-patterns-and-the-_-placeholder">Catch-All Patterns and the <code>_</code> Placeholder</a></h3>
|
||||
<p>Using enums, we can also take special actions for a few particular values, but
|
||||
for all other values take one default action. Imagine we’re implementing a game
|
||||
where, if you roll a 3 on a dice roll, your player doesn’t move but instead
|
||||
gets a fancy new hat. If you roll a 7, your player loses a fancy hat. For all
|
||||
other values, your player moves that number of spaces on the game board. Here’s
|
||||
a <code>match</code> that implements that logic, with the result of the dice roll
|
||||
hardcoded rather than a random value, and all other logic represented by
|
||||
functions without bodies because actually implementing them is out of scope for
|
||||
this example:</p>
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||||
</span> let dice_roll = 9;
|
||||
match dice_roll {
|
||||
3 => add_fancy_hat(),
|
||||
7 => remove_fancy_hat(),
|
||||
other => move_player(other),
|
||||
}
|
||||
|
||||
fn add_fancy_hat() {}
|
||||
fn remove_fancy_hat() {}
|
||||
fn move_player(num_spaces: u8) {}
|
||||
<span class="boring">}</span></code></pre>
|
||||
<p>For the first two arms, the patterns are the literal values <code>3</code> and <code>7</code>. For
|
||||
the last arm that covers every other possible value, the pattern is the
|
||||
variable we’ve chosen to name <code>other</code>. The code that runs for the <code>other</code> arm
|
||||
uses the variable by passing it to the <code>move_player</code> function.</p>
|
||||
<p>This code compiles, even though we haven’t listed all the possible values a
|
||||
<code>u8</code> can have, because the last pattern will match all values not specifically
|
||||
listed. This catch-all pattern meets the requirement that <code>match</code> must be
|
||||
exhaustive. Note that we have to put the catch-all arm last because the
|
||||
patterns are evaluated in order. If we had put the catch-all arm earlier, the
|
||||
other arms would never run, so Rust will warn us if we add arms after a
|
||||
catch-all!</p>
|
||||
<p>Rust also has a pattern we can use when we want a catch-all but don’t want to
|
||||
<em>use</em> the value in the catch-all pattern: <code>_</code> is a special pattern that matches
|
||||
any value and does not bind to that value. This tells Rust we aren’t going to
|
||||
use the value, so Rust won’t warn us about an unused variable.</p>
|
||||
<p>Let’s change the rules of the game: Now, if you roll anything other than a 3 or
|
||||
a 7, you must roll again. We no longer need to use the catch-all value, so we
|
||||
can change our code to use <code>_</code> instead of the variable named <code>other</code>:</p>
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||||
</span> let dice_roll = 9;
|
||||
match dice_roll {
|
||||
3 => add_fancy_hat(),
|
||||
7 => remove_fancy_hat(),
|
||||
_ => reroll(),
|
||||
}
|
||||
|
||||
fn add_fancy_hat() {}
|
||||
fn remove_fancy_hat() {}
|
||||
fn reroll() {}
|
||||
<span class="boring">}</span></code></pre>
|
||||
<p>This example also meets the exhaustiveness requirement because we’re explicitly
|
||||
ignoring all other values in the last arm; we haven’t forgotten anything.</p>
|
||||
<p>Finally, we’ll change the rules of the game one more time so that nothing else
|
||||
happens on your turn if you roll anything other than a 3 or a 7. We can express
|
||||
that by using the unit value (the empty tuple type we mentioned in <a href="../ch03/ch03-02-data-types.html#the-tuple-type">“The Tuple
|
||||
Type”</a><!-- ignore --> section) as the code that goes with the <code>_</code> arm:</p>
|
||||
<pre class="playground"><code class="language-rust edition2024"><span class="boring">fn main() {
|
||||
</span> let dice_roll = 9;
|
||||
match dice_roll {
|
||||
3 => add_fancy_hat(),
|
||||
7 => remove_fancy_hat(),
|
||||
_ => (),
|
||||
}
|
||||
|
||||
fn add_fancy_hat() {}
|
||||
fn remove_fancy_hat() {}
|
||||
<span class="boring">}</span></code></pre>
|
||||
<p>Here, we’re telling Rust explicitly that we aren’t going to use any other value
|
||||
that doesn’t match a pattern in an earlier arm, and we don’t want to run any
|
||||
code in this case.</p>
|
||||
<p>There’s more about patterns and matching that we’ll cover in <a href="../ch19/ch19-00-patterns.html">Chapter
|
||||
19</a><!-- ignore -->. For now, we’re going to move on to the
|
||||
<code>if let</code> syntax, which can be useful in situations where the <code>match</code> expression
|
||||
is a bit wordy.</p>
|
||||
</body>
|
||||
</html>
|
||||
Reference in New Issue
Block a user