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 clone a Rust HashMap?
- How to convert the keys of a Rust HashMap to a vector?
- How to use a custom hash function with a Rust HashMap?
- How to build a Rust HashMap from an iterator?
- How to use an enum in a Rust HashMap?
- How to convert a Rust HashMap to a JSON string?
- How to compare two Rust HashMaps?
- How to clear a Rust HashMap?
- How to get a reference to a key in a Rust HashMap?
- How to get all values from a Rust HashMap?
More of Rust
- How to convert a Rust slice to a fixed array?
- How to convert a slice of bytes to a string in Rust?
- How to match whitespace with a regex in Rust?
- How to replace strings using Rust regex?
- How to escape dots with regex in Rust?
- How to convert Rust bytes to a vector of u8?
- How to get a value by key from JSON in Rust?
- How to parse JSON string in Rust?
- How to declare a matrix in Rust?
- How to calculate the sum of a Rust slice?
See more codes...