rustHow to create a HashMap of HashMaps in Rust?
A HashMap of HashMaps can be created in Rust using the HashMap::new() method. The following example code creates a HashMap of HashMaps with String keys and i32 values:
use std::collections::HashMap;
let mut map_of_maps: HashMap<String, HashMap<String, i32>> = HashMap::new();
let mut inner_map1: HashMap<String, i32> = HashMap::new();
inner_map1.insert(String::from("key1"), 1);
inner_map1.insert(String::from("key2"), 2);
let mut inner_map2: HashMap<String, i32> = HashMap::new();
inner_map2.insert(String::from("key3"), 3);
inner_map2.insert(String::from("key4"), 4);
map_of_maps.insert(String::from("map1"), inner_map1);
map_of_maps.insert(String::from("map2"), inner_map2);
println!("{:?}", map_of_maps);
Output example
{"map1": {"key1": 1, "key2": 2}, "map2": {"key3": 3, "key4": 4}}
Code explanation
-
use std::collections::HashMap;- imports theHashMaptype from thestd::collectionsmodule. -
let mut map_of_maps: HashMap<String, HashMap<String, i32>> = HashMap::new();- creates aHashMapwithStringkeys andHashMapvalues, where theHashMapvalues haveStringkeys andi32values. -
let mut inner_map1: HashMap<String, i32> = HashMap::new();- creates aHashMapwithStringkeys andi32values. -
inner_map1.insert(String::from("key1"), 1);- inserts a key-value pair into theinner_map1HashMap. -
map_of_maps.insert(String::from("map1"), inner_map1);- inserts a key-value pair into themap_of_mapsHashMap, where the value is theinner_map1HashMap.
Helpful links
Related
- How to add an entry to a Rust HashMap?
- How to create a HashMap of structs in Rust?
- How to create a new Rust HashMap with values?
- How to lock a Rust HashMap?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to implement PartialEq for a Rust HashMap?
- How to create a HashMap of traits in Rust?
- How to create a HashMap of pointers in Rust?
- How to convert the keys of a Rust HashMap to a vector?
More of Rust
- Regex example to match multiline string in Rust?
- How to use binary regex in Rust?
- How to replace a capture group using Rust regex?
- How to match the end of a line in a Rust regex?
- How to use regex captures in Rust?
- How to match a URL with a regex in Rust?
- How to use regex to match a double quote in Rust?
- How to ignore case in Rust regex?
- How to print a Rust HashMap?
- How to split a string with Rust regex?
See more codes...