@@ -351,11 +351,28 @@ fn file_name(file_path: &str) -> Option<&str> {
351
351
```
352
352
353
353
You might think that we could use the ` map ` combinator to reduce the case
354
- analysis, but its type doesn't quite fit. Namely, ` map ` takes a function that
355
- does something only with the inner value. The result of that function is then
356
- * always* [ rewrapped with ` Some ` ] ( #code-option-map ) . Instead, we need something
357
- like ` map ` , but which allows the caller to return another ` Option ` . Its generic
358
- implementation is even simpler than ` map ` :
354
+ analysis, but its type doesn't quite fit...
355
+
356
+ ``` rust
357
+ fn file_path_ext (file_path : & str ) -> Option <& str > {
358
+ file_name (file_path ). map (| x | extension (x )) // Compilation error
359
+ }
360
+ ```
361
+
362
+ The ` map ` function here wraps the value returned by the ` extension ` function
363
+ inside an ` Option<_> ` and since the ` extension ` function itself returns an
364
+ ` Option<&str> ` the expression ` file_name(file_path).map(|x| extension(x)) `
365
+ actually returns an ` Option<Option<&str>> ` .
366
+
367
+ But since ` file_path_ext ` just returns ` Option<&str> ` (and not
368
+ ` Option<Option<&str>> ` ) we get a compilation error.
369
+
370
+ The result of the function taken by map as input is * always* [ rewrapped with
371
+ ` Some ` ] ( #code-option-map ) . Instead, we need something like ` map ` , but which
372
+ allows the caller to return a ` Option<_> ` directly without wrapping it in
373
+ another ` Option<_> ` .
374
+
375
+ Its generic implementation is even simpler than ` map ` :
359
376
360
377
``` rust
361
378
fn and_then <F , T , A >(option : Option <T >, f : F ) -> Option <A >
@@ -377,6 +394,10 @@ fn file_path_ext(file_path: &str) -> Option<&str> {
377
394
}
378
395
```
379
396
397
+ Side note: Since ` and_then ` essentially works like ` map ` but returns an
398
+ ` Option<_> ` instead of an ` Option<Option<_>> ` it is known as ` flatmap ` in some
399
+ other languages.
400
+
380
401
The ` Option ` type has many other combinators [ defined in the standard
381
402
library] [ 5 ] . It is a good idea to skim this list and familiarize
382
403
yourself with what's available—they can often reduce case analysis
0 commit comments