rustHow to create a nested HashMap in Rust?
Nested HashMap in Rust can be created using the HashMap::new() method. The following example code creates a nested HashMap with two levels of nesting:
use std::collections::HashMap;
let mut map = HashMap::new();
let mut inner_map = HashMap::new();
inner_map.insert("key1", "value1");
inner_map.insert("key2", "value2");
map.insert("inner_map", inner_map);
println!("{:?}", map);
Output example
{"inner_map": {"key1": "value1", "key2": "value2"}}
Code explanation
use std::collections::HashMap;- imports theHashMaptype from thestd::collectionsmodule.let mut map = HashMap::new();- creates a new emptyHashMapand stores it in themapvariable.let mut inner_map = HashMap::new();- creates a new emptyHashMapand stores it in theinner_mapvariable.inner_map.insert("key1", "value1");- inserts a key-value pair into theinner_mapHashMap.map.insert("inner_map", inner_map);- inserts theinner_mapHashMapinto themapHashMap.println!("{:?}", map);- prints the contents of themapHashMap.
Helpful links
Related
- How to sort the keys in a Rust HashMap?
- How to use a custom hash function with a Rust HashMap?
- How to build a Rust HashMap from an iterator?
- How to clear a Rust HashMap?
- How to check if a Rust HashMap contains a key?
- How to create a Rust HashMap?
- How to remove an element from a Rust HashMap if a condition is met?
- How to print a Rust HashMap?
- How to create a HashMap of HashMaps in Rust?
- How to create a HashMap of traits in Rust?
More of Rust
- How to replace strings using Rust regex?
- How to use regex to match a group in Rust?
- How to use regex to match a double quote in Rust?
- How to insert an element into a Rust HashMap if it does not already exist?
- Yield example in Rust
- How to compare two Rust HashMaps?
- Rust HashMap example
- Yield generator in Rust
- How to map a Rust slice?
- How to use captures_iter with regex in Rust?
See more codes...