Initialize immutable HashMap with data

HashMap from tuples keys values

Earlier we saw how to define an empty HashMap and insert values. We also saw that there is no need to define the types of a HashMap, Rust can figure that out during compilation.

Sometimes, actually probably quite rarely we would like to create a HashMap and already fill it with values. We can do that using the from method providing it an array of tuples. In each tuple the first element will become the key and the second element will become the value in the HashMap.

We don't need to explicitly tell Rust what is the type of the keys and the values of the HashMap, Rust can figure it out from the types in the tuples. In this case both the keys and the values are of type &str.

Use the keys method to get the keys

keys

println!("{:#?}", animal.keys());

Use the values method to get the values

values

println!("{:#?}", animal.values());

We cannot insert in immutable HashMap

If we try:

animal.insert("cat", "cute");

We get a compilation error:

cannot borrow `animal` as mutable, as it is not declared as mutable

It is not that surprising, after all the variable is immutable by default.

Full code

examples/hashmap/initialize-hashmap-with-data/src/main.rs

use std::collections::HashMap;

fn main() {
    let animal = HashMap::from([
        ("snake", "long"),
        ("giraffe", "tall"),
        ("elephant", "heavy"),
    ]);
    println!("{:#?}", animal);

    println!("{:#?}", animal.keys());

    println!("{:#?}", animal.values());

    // animal.insert("cat", "cute"); // cannot borrow `animal` as mutable, as it is not declared as mutable
}

Related Pages

HashMap (hash, dictionary, associative array) in Rust

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