-
Notifications
You must be signed in to change notification settings - Fork 13.4k
HashMap using &str keys is not a a realistic example #46966
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
I'm not 100% sure it's a good idea. The point is to show how to use it. It'd give a bad example if we used |
No, I think For advanced users it doesn't matter, as they'll see the But for novice users nudging towards I've filed this issue because this example has actually mislead a new Rust user. |
The issue is kinda the same: either we show users that they should use |
Choosing |
I've left one example with |
I understand your intent and I commend you for trying to address this issue. But even if the user can be confused I would still think idiomatic code has the priority, simply because idiomatic code is to be expected in every examples. In the same way, you wouldn't expect a (natural) language teaching book to give out some weird translations just for orthogonal reasons. In facts, the documentation is the main place where to learn idiomatic code, that's why it should be expected. I understand this is probably not the best place to debate it though. I'm curious to see the outcome of it. About your commits, wouldn't using |
Note that code packed in a single function, operating on string literals, is not representative of real-world Rust code. What is idiomatic for such a special case, is not idiomatic for Rust in general. In Rust's own codebase: |
Use String, not &str in some collection examples Discussed in #46966 Overuse of borrowed values in data structures is a common mistake I see in Rust user forums. Users who copy&paste such examples end up fighting with the borrow checker as soon as they replace string literals with some real values. This changes a couple of examples to use `String`, and it adds opportunity to demonstrate use of `Borrow`.
Looks like this is fixed now? |
The example in the docs uses
HashMap
of&str
:https://doc.rust-lang.org/std/collections/struct.HashMap.html#examples
but this gives bad example to users who copy the example without fully realizing consequences of using
&str
instead ofString
. Here's thread by a new user lead down a confusing path because of this example: https://users.rust-lang.org/t/how-to-pass-slice-of-structs-string-field/14586I suggest using
String
instead, even if that means a bit more noise fromto_owned()
.The text was updated successfully, but these errors were encountered: