book icon indicating copy to clipboard operation
book copied to clipboard

Simplify note about functions in ch13-01-closures.md

Open proski opened this issue 2 years ago • 3 comments
trafficstars

proski avatar Jul 13 '23 20:07 proski

The note was very hard to read, I think I had to read it about 5 times before I could fully understand it. I'm still learning Rust, so maybe it's easier for others.

Changes I made:

  • I made it clear that the Fn traits are implemented implicitly, i.e. no extra code is needed.
  • I used shorter sentences with simpler word order.
  • I reordered the sentences: statement, example, explanation, additional considerations.
  • I used scope instead of environment as environment has some irrelevant meanings (e.g. environment variables).

I also considered adding an example for Result, where a function taking one argument could be used. That would illustrate that taking arguments is not "capturing". However, I decided against it to keep the note simple.

proski avatar Jul 13 '23 20:07 proski

I've restored environment, it's used consistently in the text and it wasn't the reason the note was hard to read. I also removed the word implicitly I used in the previous version of this PR. It's actually worth noting that the Fn traits are defined implicitly by the compiler (i.e. without any code), but that text doesn't belong to the note about functions.

proski avatar Jul 18 '23 19:07 proski

Thanks for the suggestion here. I spent some time looking at this and at the original text, and while I understand why it may have been confusing, I think the original text is actually somewhat clearer here. The main thing I am still mulling on is whether we should clarify that functions implementing those traits happens automatically, i.e. the compiler does it for you as appropriate. Something like this, maybe:

Note: Functions can implement all three of the Fn traits too. 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 where we need something that implements one of the Fn traits. For example, on an Option<Vec<T>> value, we could call unwrap_or_else(Vec::new) to get a new, empty vector if the value is None. The compiler implements the Fn traits correctly and automatically for functions.

chriskrycho avatar Apr 02 '24 20:04 chriskrycho