Rust HashMap where tuples are the keys

HashMap tuple insert

examples/hash-of-tuples-as-keys/src/main.rs

use std::collections::HashMap;

fn main() {
    let mut things: HashMap<(&str, &str), &str> = HashMap::new();

    let entries= vec!["apple,red,23", "banana,green,3", "apple,red,42"];

    for entry in entries {
        let parts = entry.split(',').collect::<Vec<&str>>();
        let key = (parts[0], parts[1]);
        let value = parts[2];
        //println!("{:?}   {}", key, value);
        things.insert(key, value);

        println!("{:#?}", things);
    }

}

The third enty has the sam key as the first entry and thus the value replaces the old value.

{
    (
        "apple",
        "red",
    ): "23",
}

{
    (
        "apple",
        "red",
    ): "23",
    (
        "banana",
        "green",
    ): "3",
}

{
    (
        "apple",
        "red",
    ): "42",
    (
        "banana",
        "green",
    ): "3",
}

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