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 implement PartialEq for a Rust HashMap?
- How to use a tuple as a key in a Rust HashMap?
- How to convert a Rust HashMap to JSON?
- How to convert the keys of a Rust HashMap to a vector?
- How to convert a Rust HashMap to a JSON string?
- How to use a HashBrown with a Rust HashMap?
- How to sort the keys in a Rust HashMap?
- How to use a custom hash function with a Rust HashMap?
- How to remove an element from a Rust HashMap if a condition is met?
- How to create a Rust HashMap with a string key?
More of Rust
- How to iterate hashset in Rust
- How to get a capture group using Rust regex?
- How to use regex with bytes 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 compile a regex in Rust?
- How to use regex to match a double quote in Rust?
- How to replace all using regex in Rust?
- How to use regex to match a group in Rust?
- How to calculate the inverse of a matrix in Rust?
See more codes...