From 60b198a27f8e89c45d61df4bc2a1e493d764045d Mon Sep 17 00:00:00 2001 From: Chris Krycho Date: Thu, 12 Dec 2024 08:49:16 -0700 Subject: [PATCH] Further clarify note about functions implementing `Fn` traits --- src/ch13-01-closures.md | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/ch13-01-closures.md b/src/ch13-01-closures.md index e4989eb5c3..38aaaa25ef 100644 --- a/src/ch13-01-closures.md +++ b/src/ch13-01-closures.md @@ -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>`. -> 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>` 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