Check if key exists in HashMap - if the HashMap contains the key

HashMap contains_key exists

If you'd like to know if a given key exists in a given HashMap you can use the contains_key method that will return a bool, that's either True of False.


use std::collections::HashMap;

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

    animal.insert(String::from("snake"), String::from("long"));
    animal.insert(String::from("giraffe"), String::from("tall"));
    animal.insert(String::from("elephant"), String::from("heavy"));

    println!("{:#?}", animal);
    for name in ["turle", "snake"] {
        if animal.contains_key(name) {
            println!("{name} is in the HashMap and it is {}", animal[name]);
        } else {
            println!("{name} is NOT in the HashMap");

Related Pages

HashMap (hash, dictionary, associative array) in Rust
Given a key, get value from a HashMap


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