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 convert the keys of a Rust HashMap to a vector?
- How to create a new Rust HashMap with values?
- How to convert a Rust HashMap to JSON?
- How to get the length of a Rust HashMap?
- How to convert a Rust HashMap to a BTreeMap?
- How to remove an element from a Rust HashMap if a condition is met?
- How to insert an element into a Rust HashMap if it does not already exist?
- How to use an enum in a Rust HashMap?
- How to create a HashMap of HashMaps in Rust?
More of Rust
- How to replace a capture group using Rust regex?
- How to get an element from a HashSet in Rust?
- How to replace strings using Rust regex?
- How to use enum as hashmap key in Rust
- How to use non-capturing groups in Rust regex?
- How to iterate and modify a vector in Rust
- How to use regex lookahead in Rust?
- How to match a URL with a regex in Rust?
- How to match the end of a line in a Rust regex?
- How to get a capture group using Rust regex?
See more codes...