Skip to content

Commit

Permalink
Further clarify note about functions implementing Fn traits
Browse files Browse the repository at this point in the history
  • Loading branch information
chriskrycho authored Dec 12, 2024
1 parent 5190136 commit 60b198a
Showing 1 changed file with 6 additions and 5 deletions.
11 changes: 6 additions & 5 deletions src/ch13-01-closures.md
Original file line number Diff line number Diff line change
Expand Up @@ -332,11 +332,12 @@ called. If the `Option` is `None`, `f` will be called once. Because all
closures implement `FnOnce`, `unwrap_or_else` accepts the most different kinds
of closures and is as flexible as it can be.

> Note: Functions can be used in place of closures in some cases. For example,
> we could call `unwrap_or_else(Vec::new)` on a value of type `Option<Vec<T>>`.
> If the value is `None`, we would get a new, empty vector. It works because
> functions implement the `Fn` traits just like closures. However, only
> closures can capture variables from the environment, functions cannot do it.
> Note: If what we want to do doesn’t require capturing a value from the
> environment, we can use the name of a function rather than a closure. For
> example, we could call `unwrap_or_else(Vec::new)` on a `Option<Vec<T>>` value
> to get a new, empty vector if the value is `None`. The compiler automatically
> implements whichever of the `Fn` traits is applicable for a function
> definition.
Now let’s look at the standard library method `sort_by_key` defined on slices,
to see how that differs from `unwrap_or_else` and why `sort_by_key` uses
Expand Down

0 comments on commit 60b198a

Please sign in to comment.