Open ndim opened 1 year ago
This is an interesting one. It’s definitely a valuable feature to know about, but the book also can't be exhaustive. I flagged it for us to think about as we look at the next revision, but I think it is probably one of those things that is advanced enough and relatively rare enough that it doesn't make sense to put in the main book! We'll see.
I have searched open and closed issues and pull requests for duplicates, using these search terms:
I have checked the latest
main
branch to see if this has already been fixed, in this file:Neither of those files mention
const
.URL to the section(s) of the book with this problem: book: https://doc.rust-lang.org/book/ch10-02-traits.html#default-implementations source: src/ch10-02-traits.md
Description of the problem:
When describing traits, the book only describes
fn
items as part of the trait. However, it appears thatconst
items can also be part of atrait
, and be especially useful in connection with default implementations offn
items.Suggested fix:
I would have found it helpful if an example of the following type and possibly more discussion about
const
intrait
would have been in the "Default Implementations" section of src/ch10-02-traits.md.If using
const
inside atrait
is considered too advanced for inclusion in the basic chapter on traits, mentioning thatconst
can be a part of atrait
might also fit into src/ch19-03-advanced-traits.md.I might also be wrong about this belonging in the book (I am too new to Rust to judge that).
const
-in-trait
just seems to solve a not too uncommon problem for someone writing software for about the last 25 years, andconst
-in-trait
not being mentioned in the book at all surprised me.Minimum working example:
I ran into this when converting different decibel values to and from
u32
values sent to and received from a USB device, and needing to parse such values from strings as command line arguments. The three device parameters all use different numeric ranges, but they all have a common behaviour for parsing the CLI argument string into a numeric value and converting fromf64
decibel value to theu32
integer value the device uses and vice versa.I found
const
-in-trait
somewhere on the internet, wondered why the book did not mention that at all, and then dav1d on the#rust
IRC channel said that it was ok to useconst
-in-trait
, so I wrote this issue.I might come up with a better example for illustrating
const
-in-trait
which explains it better and in a more useful manner than thetrait Multiplier
example, but is not as complex as the three decibel conversions.