2
2
3
3
The ` if let ` syntax lets you combine ` if ` and ` let ` into a less verbose way to
4
4
handle values that match one pattern while ignoring the rest. Consider the
5
- program in Listing 6-6 that matches on an ` Option<u8> ` value but only wants to
6
- execute code if the value is 3 .
5
+ program in Listing 6-6 that matches on an ` Option<u8> ` value in the ` config_max `
6
+ variable but only wants to execute code if the value is the ` Some ` variant .
7
7
8
8
``` rust
9
9
{{#rustdoc_include .. / listings / ch06 - enums - and - pattern - matching / listing - 06 - 06 / src / main . rs: here }}
10
10
```
11
11
12
12
<span class =" caption " >Listing 6-6: A ` match ` that only cares about executing
13
- code when the value is ` Some(3) ` </span >
13
+ code when the value is ` Some ` </span >
14
14
15
- We want to do something with the ` Some(3) ` match but do nothing with any other
16
- ` Some<u8> ` value or the ` None ` value. To satisfy the ` match ` expression, we
17
- have to add ` _ => () ` after processing just one variant, which is a lot of
18
- boilerplate code to add.
15
+ If the value is ` Some ` , we want to print out the value in the ` Some ` variant,
16
+ which we do by binding the value to the variable ` max ` in the pattern.
17
+ We don’t want to do anything with the ` None ` value. To satisfy the ` match `
18
+ expression, we have to add ` _ => () ` after processing just one variant, which
19
+ is annoying boilerplate code to add.
19
20
20
21
Instead, we could write this in a shorter way using ` if let ` . The following
21
22
code behaves the same as the ` match ` in Listing 6-6:
@@ -26,7 +27,11 @@ code behaves the same as the `match` in Listing 6-6:
26
27
27
28
The syntax ` if let ` takes a pattern and an expression separated by an equal
28
29
sign. It works the same way as a ` match ` , where the expression is given to the
29
- ` match ` and the pattern is its first arm.
30
+ ` match ` and the pattern is its first arm. In this case, the pattern is
31
+ ` Some(max) ` , and the ` max ` binds to the value inside the ` Some ` . We can then
32
+ use ` max ` in the body of the ` if let ` block in the same way as we used ` max ` in
33
+ the corresponding ` match ` arm. The code in the ` if let ` block isn’t run if the
34
+ value doesn’t match the pattern.
30
35
31
36
Using ` if let ` means less typing, less indentation, and less boilerplate code.
32
37
However, you lose the exhaustive checking that ` match ` enforces. Choosing
0 commit comments