Maps in Rust

Maps are Rust’s built-in associative data type (sometimes called hashes or dicts in other languages).

To create an empty map, use the HashMap::new method.

use std::collections::HashMap;

fn main() {
    let mut m = HashMap::new();

Set key/value pairs using typical name.insert(key, val) syntax.

    m.insert("k1", 7);
    m.insert("k2", 13);

Printing a map with e.g. println! will show all of its key/value pairs.

    println!("map: {:?}", m);

Get a value for a key with name.get(key).

    if let Some(v1) = m.get("k1") {
        println!("v1: {}", v1);
    }

If the key doesn’t exist, the Option::None is returned.

    let v3 = m.get("k3").unwrap_or(&0);
    println!("v3: {}", v3);

The len method returns the number of key/value pairs.

    println!("len: {}", m.len());

The HashMap::remove method removes key/value pairs from a map.

    m.remove("k2");
    println!("map: {:?}", m);

Clearing all key/value pairs from a map can be done with the clear method.

    m.clear();
    println!("map: {:?}", m);

The contains_key method can be used to check if a key is present in the map.

    let prs = m.contains_key("k2");
    println!("prs: {}", prs);

You can also declare and initialize a new map in the same line with this syntax.

    let mut n = HashMap::new();
    n.insert("foo", 1);
    n.insert("bar", 2);
    println!("map: {:?}", n);

In Rust, you can compare two maps for equality using the == operator.

    let mut n2 = HashMap::new();
    n2.insert("foo", 1);
    n2.insert("bar", 2);
    if n == n2 {
        println!("n == n2");
    }
}

Note that maps appear in the form {"k": v, "k": v} when printed with println!.

$ cargo run
map: {"k1": 7, "k2": 13}
v1: 7
v3: 0
len: 2
map: {"k1": 7}
map: {}
prs: false
map: {"bar": 2, "foo": 1}
n == n2