Create empty HashMap and insert key-value pairs

HashMap mut new insert :#?

HashMap in Rust is a data-structure holding key-value pairs.

Declare and initialize empty HashMap

We can declare a variable, define the type of it and initialize it using the following command:

let length_of: HashMap<String, u32> = HashMap::new();

This means that the keys of this HashMap will be of type String and the values will be of type u32.

The keys can be other things as well, for example we can have a HashMap with tuples as keys.

You might be also wondering why do you need to mention HashMap twice in that line. You don't. You can also rely on rust figuring out the type of the HashMap.

Declare and initialize an empty but mutable HashMap

However the above declaration is rather useless as we cannot change the content of that variable.

We need to declare it to be mutable using the mut keyword:

let mut length_of: HashMap<String, u32> = HashMap::new();

Insert key-value pairs in the HashMap

We can use the insert method to, well, insert key-value pairs:

length_of.insert(String::from("snake"), 320);

The size of the HashMap - the number of key-value pairs

The len method returns the length of the HashMap which is the number of pairs in the HashMap.

The :#? formatting option helps print the HashMap in a more human-readable format.

The full code

examples/hashmap/create-empty-hashmap/src/main.rs

use std::collections::HashMap;

fn main() {
    let mut length_of: HashMap<String, u32> = HashMap::new();
    println!("{}", length_of.len());
    println!("{:#?}", length_of);
    println!();

    length_of.insert(String::from("snake"), 320);
    println!("{}", length_of.len());
    println!("{:#?}", length_of);
    println!();

    length_of.insert(String::from("snail"), 4);
    println!("{}", length_of.len());
    println!("{:#?}", length_of);

}

0
{}

1
{
    "snake": 320,
}

2
{
    "snail": 4,
    "snake": 320,
}

Related Pages

Initialize immutable HashMap with data
HashMap (hash, dictionary, associative array) in Rust
Create empty HashMap in Rust without type definition
Create empty HashMap in Rust without type definition

Author

Gabor Szabo (szabgab)

Gabor Szabo, the author of the Rust Maven web site maintains several Open source projects in Rust and while he still feels he has tons of new things to learn about Rust he already offers training courses in Rust and still teaches Python, Perl, git, GitHub, GitLab, CI, and testing.

Gabor Szabo