rust-lang / book

The Rust Programming Language
https://doc.rust-lang.org/book/
Other
15.28k stars 3.44k forks source link

Add remark about Fn trait hierarchy in Chapter 13 #4068

Closed kardwen closed 1 month ago

kardwen commented 1 month ago

I found this explanation for FnMut in the documentation helpful, which explicitly points out the hierarchy of Fn traits, i.e. subtraits and supertraits:

FnMut is implemented automatically by closures which take mutable references to captured variables, as well as all types that implement Fn, e.g., (safe) function pointers (since FnMut is a supertrait of Fn). Additionally, for any type F that implements FnMut, &mut F implements FnMut, too.

Since FnOnce is a supertrait of FnMut, any instance of FnMut can be used where a FnOnce is expected, and since Fn is a subtrait of FnMut, any instance of Fn can be used where FnMut is expected.

Maybe this can also be added to chapter 13 where the Fn traits are introduced? It is kind of described in this sentence, but it did not immediately occur to me:

Closures will automatically implement one, two, or all three of these Fn traits, in an additive fashion, depending on how the closure’s body handles the values:[...]

Maybe the following examples would be easier to understand if the relationship between FnOnce, FnMut and Fn were made explicit a second time?

chriskrycho commented 1 month ago

Thanks for the suggestion. The book doesn’t introduce the idea of supertraits until 19.2: Advanced Traits – Using Supertraits to Require One Trait’s Functionality Within Another Trait, so introducing the hierarchy here would require a bunch of extra explanation. I think it’s probably better to leave it as is, where someone who wants to dive deeper will find it in the documentation (as you did!) and folks reading linearly through the book will not have to think about that particular relationship. This is a weird/difficult balance to strike!

kardwen commented 1 month ago

Okay, thanks! I hope I can finish the book soon and that the issues I have opened are not too much of an annoyance.

chriskrycho commented 1 month ago

No annoyance at all – they’re informative about what is or isn’t working for individual readers, and even if we close them like this, we appreciate the consideration!