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 HashBrown with a Rust HashMap?
- How to use a custom hash function with 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 insert an element into a Rust HashMap if it does not already exist?
- How to sort a Rust HashMap?
- How to pop an element from a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
- How to create a new Rust HashMap with values?
More of Rust
- How to match whitespace with a regex in Rust?
- How to use non-capturing groups in Rust regex?
- How to match a URL with a regex in Rust?
- How to replace a capture group using Rust regex?
- How to get a capture group using Rust regex?
- How to calculate the inverse of a matrix in Rust?
- How to replace strings using Rust regex?
- How to split a string with Rust regex?
- Pointer comparison in Rust
- How to replace all matches using Rust regex?
See more codes...