find the length of a map in rust

To find the length of a HashMap (or any type implementing the std::collections::HashMap trait) in Rust, you can use the len() method provided by the trait. Here's an example:

main.rs
use std::collections::HashMap;

fn main() {
    let mut my_map = HashMap::new();
    my_map.insert("foo", 42);
    my_map.insert("bar", 123);

    println!("The length of the map is: {}", my_map.len());
}
205 chars
10 lines

In this example, a new HashMap is created and two key-value pairs are added to it. The len() method is then called on the map to find its length, which is printed to the console.

Note that len() returns the number of key-value pairs in the map, not the total number of elements. If you need to find the total number of elements, you can multiply the length by the size of the key-value pair, which can be found using the mem::size_of_val() function.

related categories

gistlibby LogSnag