How I can create a HashMap literal in Rust? In Python I can do it so:
hashmap = {
\'element0\': {
\'name\': \'My New Element\',
\'childs\':
If you wish to initialize the map with only one element in one line (and without visible mutation in your code), you could do:
let map: HashMap<&'static str, u32> = Some(("answer", 42)).into_iter().collect();
This is thanks to the usefulness of Option being able to become an Iterator using into_iter().
In real code, you probably don't need to help the compiler with the type:
use std::collections::HashMap;
fn john_wick() -> HashMap<&'static str, u32> {
Some(("answer", 42)).into_iter().collect()
}
fn main() {
let result = john_wick();
let mut expected = HashMap::new();
expected.insert("answer", 42);
assert_eq!(result, expected);
}
There is also a way to chain this to have more than one element doing something like Some(a).into_iter().chain(Some(b).into_iter()).collect()
, but this is longer, less readable and probably has some optimization issues, so I advise against it.