File tree 1 file changed +80
-1
lines changed
1 file changed +80
-1
lines changed Original file line number Diff line number Diff line change 1
1
% if let
2
2
3
- COMING SOON
3
+ ` if let ` allows you to combine ` if ` and ` let ` together to reduce the overhead
4
+ of certain kinds of pattern matches.
5
+
6
+ For example, let’s say we have some sort of ` Option<T> ` . We want to call a function
7
+ on it if it’s ` Some<T> ` , but do nothing if it’s ` None ` . That looks like this:
8
+
9
+ ``` rust
10
+ # let option = Some (5 );
11
+ # fn foo (x : i32 ) { }
12
+ match option {
13
+ Some (x ) => { foo (x ) },
14
+ None => {},
15
+ }
16
+ ```
17
+
18
+ We don’t have to use ` match ` here, for example, we could use ` if ` :
19
+
20
+ ``` rust
21
+ # let option = Some (5 );
22
+ # fn foo (x : i32 ) { }
23
+ if option . is_some () {
24
+ let x = option . unwrap ();
25
+ foo (x );
26
+ }
27
+ ```
28
+
29
+ Neither of these options is particularly appealing. We can use ` if let ` to
30
+ do the same thing in a nicer way:
31
+
32
+ ``` rust
33
+ # let option = Some (5 );
34
+ # fn foo (x : i32 ) { }
35
+ if let Some (x ) = option {
36
+ foo (x );
37
+ }
38
+ ```
39
+
40
+ If a [ pattern] [ patterns ] matches successfully, it binds any appropriate things
41
+ from the pattern, then runs the code from the block. If the pattern doesn’t
42
+ match, nothing happens.
43
+
44
+ If you’d rather to do something else when the pattern does not match, you can
45
+ use ` else ` :
46
+
47
+ ``` rust
48
+ # let option = Some (5 );
49
+ # fn foo (x : i32 ) { }
50
+ # fn bar () { }
51
+ if let Some (x ) = option {
52
+ foo (x );
53
+ } else {
54
+ bar ();
55
+ }
56
+ ```
57
+
58
+ ## ` while let `
59
+
60
+ In a similar fashion, ` while let ` can be used when you want to loop over the
61
+ result of a pattern. It turns code like this:
62
+
63
+ ``` rust
64
+ # let option : Option <i32 > = None ;
65
+ loop {
66
+ match option {
67
+ Some (x ) => println! (" {}" , x ),
68
+ _ => break ,
69
+ }
70
+ }
71
+ ```
72
+
73
+ Into code like this:
74
+
75
+ ``` rust
76
+ # let option : Option <i32 > = None ;
77
+ while let Some (x ) = option {
78
+ println! (" {}" , x );
79
+ }
80
+ ```
81
+
82
+ [ patterns ] : patterns.html
You can’t perform that action at this time.
0 commit comments