Skip to content

Commit 78afc78

Browse files
committed
Rollup merge of rust-lang#30971 - SDX2000:docfixes, r=steveklabnik
Updated documentation to clarify the difference between `and_then` and `map`. This also explains why we need `and_then` in addition to `map`. Please look at the diff for more information. r? @alexcrichton
2 parents a4a249f + 0922d7e commit 78afc78

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

src/doc/book/error-handling.md

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -356,11 +356,28 @@ fn file_name(file_path: &str) -> Option<&str> {
356356
```
357357

358358
You might think that we could use the `map` combinator to reduce the case
359-
analysis, but its type doesn't quite fit. Namely, `map` takes a function that
360-
does something only with the inner value. The result of that function is then
361-
*always* [rewrapped with `Some`](#code-option-map). Instead, we need something
362-
like `map`, but which allows the caller to return another `Option`. Its generic
363-
implementation is even simpler than `map`:
359+
analysis, but its type doesn't quite fit...
360+
361+
```rust,ignore
362+
fn file_path_ext(file_path: &str) -> Option<&str> {
363+
file_name(file_path).map(|x| extension(x)) //Compilation error
364+
}
365+
```
366+
367+
The `map` function here wraps the value returned by the `extension` function
368+
inside an `Option<_>` and since the `extension` function itself returns an
369+
`Option<&str>` the expression `file_name(file_path).map(|x| extension(x))`
370+
actually returns an `Option<Option<&str>>`.
371+
372+
But since `file_path_ext` just returns `Option<&str>` (and not
373+
`Option<Option<&str>>`) we get a compilation error.
374+
375+
The result of the function taken by map as input is *always* [rewrapped with
376+
`Some`](#code-option-map). Instead, we need something like `map`, but which
377+
allows the caller to return a `Option<_>` directly without wrapping it in
378+
another `Option<_>`.
379+
380+
Its generic implementation is even simpler than `map`:
364381

365382
```rust
366383
fn and_then<F, T, A>(option: Option<T>, f: F) -> Option<A>
@@ -382,6 +399,10 @@ fn file_path_ext(file_path: &str) -> Option<&str> {
382399
}
383400
```
384401

402+
Side note: Since `and_then` essentially works like `map` but returns an
403+
`Option<_>` instead of an `Option<Option<_>>` it is known as `flatmap` in some
404+
other languages.
405+
385406
The `Option` type has many other combinators [defined in the standard
386407
library][5]. It is a good idea to skim this list and familiarize
387408
yourself with what's available—they can often reduce case analysis

0 commit comments

Comments
 (0)