@@ -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> ` .
1212Using ` 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+
5157fn 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