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 theHashMap
type from thestd::collections
module.let mut map = HashMap::new();
- creates a new emptyHashMap
and stores it in themap
variable.let mut inner_map = HashMap::new();
- creates a new emptyHashMap
and stores it in theinner_map
variable.inner_map.insert("key1", "value1");
- inserts a key-value pair into theinner_map
HashMap
.map.insert("inner_map", inner_map);
- inserts theinner_map
HashMap
into themap
HashMap
.println!("{:?}", map);
- prints the contents of themap
HashMap
.
Helpful links
Related
- How to use an enum in a Rust HashMap?
- How to convert a Rust HashMap to a BTreeMap?
- How to compare two Rust HashMaps?
- How to create a new Rust HashMap with values?
- How to use an enum as a key in a Rust HashMap?
- How to clone a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
- How to clear a Rust HashMap?
- How to check if a Rust HashMap contains a key?
- How to build a Rust HashMap from an iterator?
More of Rust
- How to replace a capture group using Rust regex?
- How to replace strings using Rust regex?
- How to use regex lookbehind in Rust?
- How to use regex with bytes in Rust?
- How to parse JSON string in Rust?
- Regex example to match multiline string in Rust?
- How to match the end of a line in a Rust regex?
- How to use regex to match a double quote in Rust?
- How to perform matrix operations in Rust?
- How to extract data with regex in Rust?
See more codes...