Description
Proposal
Add a hash_map!
macro that would possibly generate a HashMap
instead of using HashMap::from([])
which doesn't feel that idiomatic.
This isn't a performance addition, and wouldn't really change anything else more than add an idiomatic way of creating HashMap
s.
Problem statement
Adding this macro would allow to make code cleaner, instead of having an iterable of tuples that is then collected to a HashMap we would have a more idiomatic macro at the style of vec!
and this would possibly be an addition and motivation to make this for further structures.
Motivating examples or use cases
I made a library, which has templates, to fill these there is a HashMap<K: ToString, V: ToString>
parameter, creating that is quite bulky for the user. The only way for it to not be bulky is to create that step by step, but sometimes this parameter will be simply a HashMap::from
instantiation.
let translations = TestContext::load_translations(
Language::ES,
&HashMap::from([
("user", "John")
])
)
Solution sketch
The macro would look something along the lines of
hash_map!{
"key" => "value",
"key" => "value"
}
and this could directly generate a call to HashMap::from
such as
macro_rules! hash_map {
($($key:expr => $value:expr),* $(,)?) => {{
std::collections::HashMap::from([
$(($key, $value)),*
])
}}
}
Alternatives
This is too small to be made a crate, and re-implementing the macro on every project feels bulky.
Links and related work
What happens now?
This issue contains an API change proposal (or ACP) and is part of the libs-api team feature lifecycle. Once this issue is filed, the libs-api team will review open proposals as capability becomes available. Current response times do not have a clear estimate, but may be up to several months.
Possible responses
The libs team may respond in various different ways. First, the team will consider the problem (this doesn't require any concrete solution or alternatives to have been proposed):
- We think this problem seems worth solving, and the standard library might be the right place to solve it.
- We think that this probably doesn't belong in the standard library.
Second, if there's a concrete solution:
- We think this specific solution looks roughly right, approved, you or someone else should implement this. (Further review will still happen on the subsequent implementation PR.)
- We're not sure this is the right solution, and the alternatives or other materials don't give us enough information to be sure about that. Here are some questions we have that aren't answered, or rough ideas about alternatives we'd want to see discussed.