Skip to content

Commit 1d082de

Browse files
committed
Rollup merge of #24643 - steveklabnik:doc_if_let, r=jakub-
and while let
2 parents d09a0cd + 570b250 commit 1d082de

File tree

1 file changed

+80
-1
lines changed

1 file changed

+80
-1
lines changed

src/doc/trpl/if-let.md

+80-1
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,82 @@
11
% if let
22

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 parts of
41+
the value to the identifiers in the pattern, then evaluates the expression. If
42+
the pattern doesn’t 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 conditionally
61+
loop as long as a value matches a certain 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

0 commit comments

Comments
 (0)