Pass a mutable hash to a function in Rust

HashMap to_owned fn &mut or_insert

examples/fill-a-hash-in-a-function/src/main.rs

use std::collections::HashMap;

fn main() {
    let mut count: HashMap<String, u32> = HashMap::new();
    add(&mut count, &["camel", "snake", "crab", "crab"]);
    add(&mut count, &["camel", "camel", "crab", "crab"]);

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

fn add(counter: &mut HashMap<String, u32>, words: &[&str]) {
    for word in words {
        *counter.entry(word.to_owned().to_owned()).or_insert(0) += 1;
    }
}


The output

{
    "crab": 4,
    "camel": 3,
    "snake": 1,
}

See also Pass a mutable vector to a function 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