3 ms·
Has anyone struggled with the lack of HashMap literal? https://github.com/rust-lang/rfcs/issues/542 https://github.com/rust-lang/rfcs/issues/542 I just cant b
by svnpenn 7y ago
Has anyone struggled with the lack of HashMap literal?
https://github.com/rust-lang/rfcs/issues/542 https://github.com/rust-lang/rfcs/issues/542
I just cant bring myself to doing something like this:
let m1: HashMap<&str, i32> = [("Sun", 10), ("Mon", 11)].
iter().
cloned().
collect();
https://doc.rust-lang.org/std/collections/struct.HashMap.html https://doc.rust-lang.org/std/collections/struct.HashMap.htm...
- dmit 7y agoWould a macro work ok for you, like the inbuilt vec! one? There's a crate for that named maplit: https://docs.rs/maplit https://docs.rs/maplit let map = hashmap!{ "a" => 1, "b" => 2, };
- gameswithgo 7y agoone of the fun things about Rust, is any time you think "man I wish there was some syntax to do this thing in Rust" you can make a macro to make it reality, usually one already exists.
- j1elo 7y agoI assume it must be a common finding. I have too wanted to initialize a map value with a literal, only to find that one needs to juggle around their absence. Very weird thing to miss in such a great language, really. I guess that the syntax proposal would get too complicated with all the different possibilities (like what happens if you want to store one ref, now you need to add lifetimes and such), but overall for the novice it just looks like a strange thing to not have.
- gameswithgo 7y agoyou can so easily make a macro in rust to do exactly what you want, that it doesn't likely make sense to include it as part of the language. though perhaps the macro should be in the core libs.
- j1elo 7y agoYeah, probably such a macro for maps should be provided in the core libs. It would be more consistent with providing the equivalent one for vecs. From a user (of the language) perspective, having one but not the other is just confusing. Also writing macros is not the first thing one learns when getting to know Rust, so a learner won't know how to write her own.
- taktoa 7y agoYou shouldn't be writing literal HashMaps in your code very often anyway; you should use a function that pattern matches on a string for the day-of-week-to-number example (returning Option of course). Most other cases where you might want literal HashMaps are well-served by either pattern matching functions or structs. The point of a HashMap is that it has keys that you don't know at compile-time; if you use a HashMap literal, that's basically saying that you do know the keys at compile time.