book
book copied to clipboard
Simplify note about functions in ch13-01-closures.md
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
Fntraits 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
scopeinstead ofenvironmentasenvironmenthas 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.
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.
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
Fntraits 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 theFntraits. For example, on anOption<Vec<T>>value, we could callunwrap_or_else(Vec::new)to get a new, empty vector if the value isNone. The compiler implements theFntraits correctly and automatically for functions.