@@ -8,7 +8,7 @@ known in some languages as flatmap, comes in.
8
8
9
9
` and_then() ` calls its function input with the wrapped value and returns the result. If the ` Option ` is ` None ` , then it returns ` None ` instead.
10
10
11
- In the following example, ` cookable_v2 ()` results in an ` Option<Food> ` .
11
+ In the following example, ` cookable_v3 ()` results in an ` Option<Food> ` .
12
12
Using ` map() ` instead of ` and_then() ` would have given an
13
13
` Option<Option<Food>> ` , which is an invalid type for ` eat() ` .
14
14
@@ -44,12 +44,18 @@ fn cookable_v1(food: Food) -> Option<Food> {
44
44
}
45
45
46
46
// 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> {
48
48
have_recipe(food).and_then(have_ingredients)
49
49
}
50
50
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
+
51
57
fn eat(food: Food, day: Day) {
52
- match cookable_v2 (food) {
58
+ match cookable_v3 (food) {
53
59
Some(food) => println!("Yay! On {:?} we get to eat {:?}.", day, food),
54
60
None => println!("Oh no. We don't get to eat on {:?}?", day),
55
61
}
@@ -66,8 +72,9 @@ fn main() {
66
72
67
73
### See also:
68
74
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 ]
70
76
71
77
[ closures ] : ../../fn/closures.md
72
78
[ option ] : https://doc.rust-lang.org/std/option/enum.Option.html
73
79
[ 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