How I can create a HashMap literal in Rust? In Python I can do it so:
hashmap = {
\'element0\': {
\'name\': \'My New Element\',
\'childs\':
As noted by @Johannes in the comments, it's possible to use vec![]
because:
Vec
implements the IntoIterator
traitHashMap
implements FromIterator
which means you can do this:
let map: HashMap = vec![("key".to_string(), "value".to_string())]
.into_iter()
.collect();
You can use &str
but you might need to annotate lifetimes if it's not 'static
:
let map: HashMap<&str, usize> = vec![("one", 1), ("two", 2)].into_iter().collect();