Skip to content

Commit a071456

Browse files
authored
Merge pull request #1710 from vlazzle/and_then-example-flatten
Expand `Option::and_then` example to contrast with `map`
2 parents db8e52a + ef545c6 commit a071456

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

src/error/option_unwrap/and_then.md

+11-4
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ known in some languages as flatmap, comes in.
88

99
`and_then()` calls its function input with the wrapped value and returns the result. If the `Option` is `None`, then it returns `None` instead.
1010

11-
In the following example, `cookable_v2()` results in an `Option<Food>`.
11+
In the following example, `cookable_v3()` results in an `Option<Food>`.
1212
Using `map()` instead of `and_then()` would have given an
1313
`Option<Option<Food>>`, which is an invalid type for `eat()`.
1414

@@ -44,12 +44,18 @@ fn cookable_v1(food: Food) -> Option<Food> {
4444
}
4545
4646
// This can conveniently be rewritten more compactly with `and_then()`:
47-
fn cookable_v2(food: Food) -> Option<Food> {
47+
fn cookable_v3(food: Food) -> Option<Food> {
4848
have_recipe(food).and_then(have_ingredients)
4949
}
5050
51+
// Otherwise we'd need to `flatten()` an `Option<Option<Food>>`
52+
// to get an `Option<Food>`:
53+
fn cookable_v2(food: Food) -> Option<Food> {
54+
have_recipe(food).map(have_ingredients).flatten()
55+
}
56+
5157
fn eat(food: Food, day: Day) {
52-
match cookable_v2(food) {
58+
match cookable_v3(food) {
5359
Some(food) => println!("Yay! On {:?} we get to eat {:?}.", day, food),
5460
None => println!("Oh no. We don't get to eat on {:?}?", day),
5561
}
@@ -66,8 +72,9 @@ fn main() {
6672

6773
### See also:
6874

69-
[closures][closures], [`Option`][option], and [`Option::and_then()`][and_then]
75+
[closures][closures], [`Option`][option], [`Option::and_then()`][and_then], and [`Option::flatten()`][flatten]
7076

7177
[closures]: ../../fn/closures.md
7278
[option]: https://doc.rust-lang.org/std/option/enum.Option.html
7379
[and_then]: https://doc.rust-lang.org/std/option/enum.Option.html#method.and_then
80+
[flatten]: https://doc.rust-lang.org/std/option/enum.Option.html#method.flatten

0 commit comments

Comments
 (0)