rustHow to get the length of a Rust HashMap?
The length of a Rust HashMap can be obtained using the len()
method.
Example code
use std::collections::HashMap;
let mut map = HashMap::new();
map.insert("a", 1);
map.insert("b", 2);
println!("Length of map: {}", map.len());
Output example
Length of map: 2
Code explanation
use std::collections::HashMap;
- imports theHashMap
type from thestd::collections
module.let mut map = HashMap::new();
- creates a new emptyHashMap
instance.map.insert("a", 1);
- inserts a key-value pair into theHashMap
.map.insert("b", 2);
- inserts another key-value pair into theHashMap
.println!("Length of map: {}", map.len());
- prints the length of theHashMap
to the console.
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 clone a Rust HashMap?
- How to use an enum as a key in 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?
- How to create a Rust HashMap with a string key?
More of Rust
- How to replace strings using Rust regex?
- How to compile a regex in Rust?
- How to use regex to match a double quote 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 use regex with bytes in Rust?
- How to calculate the inverse of a matrix in Rust?
- How to parse JSON string in Rust?
- How to get an entry from a HashSet in Rust?
- How to yield a thread in Rust?
See more codes...