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 theHashMap
type from thestd::collections
module. -
let mut map_of_maps: HashMap<String, HashMap<String, i32>> = HashMap::new();
- creates aHashMap
withString
keys andHashMap
values, where theHashMap
values haveString
keys andi32
values. -
let mut inner_map1: HashMap<String, i32> = HashMap::new();
- creates aHashMap
withString
keys andi32
values. -
inner_map1.insert(String::from("key1"), 1);
- inserts a key-value pair into theinner_map1
HashMap
. -
map_of_maps.insert(String::from("map1"), inner_map1);
- inserts a key-value pair into themap_of_maps
HashMap
, where the value is theinner_map1
HashMap
.
Helpful links
Related
- How to convert the keys of a Rust HashMap to a vector?
- How to convert a Rust HashMap to a JSON string?
- How to convert a Rust HashMap to JSON?
- How to convert a Rust HashMap to a struct?
- How to use a custom hash function with a Rust HashMap?
- How to clone a Rust HashMap?
- How to build a Rust HashMap from an iterator?
- How to use a custom hasher with a Rust HashMap?
- How to use an enum in a Rust HashMap?
- How to compare two Rust HashMaps?
More of Rust
- How to use a custom hash function with a Rust HashMap?
- How to yield a thread in Rust?
- How to split a string by regex in Rust?
- How to convert Rust bytes to a vector of u8?
- How to use named capture groups in Rust regex?
- How to add matrices in Rust?
- How to replace a capture group using Rust regex?
- How to calculate the sum of a Rust slice?
- How to replace strings using Rust regex?
- How to display enum in Rust
See more codes...