Rust Program to Get key from HashMap using the value


Get key from HashMap using the value

Rust Programming Language


Get key from HashMap using the value


Problem


Rust program that retrieves a key from a HashMap using its associated value.

Input


use std::collections::HashMap;

fn get_key_by_value<'a, K, V>(map: &'a HashMap<K, V>, value: &V) -> Option<&'a K>
where
    K: std::cmp::Eq + std::hash::Hash,
    V: std::cmp::Eq,
{
    for (key, val) in map {
        if val == value {
            return Some(key);
        }
    }
    None
}

fn main() {
    let mut map = HashMap::new();
    map.insert(1, "one");
    map.insert(2, "two");
    map.insert(3, "three");

    let value = "two";
    let key = get_key_by_value(&map, &value);

    match key {
        Some(k) => println!("Key for value {}: {}", value, k),
        None => println!("No key found for value {}", value),
    }
}{codeBox}

Output


Key for value two: 2{codeBox}

Explanation


This program defines a get_key_by_value function that takes a reference to a HashMap and a reference to a value, and returns an Option containing a reference to the key associated with that value in the map, or None if no such key exists.

The get_key_by_value function iterates over the key-value pairs in the map using a for loop, checking if the value of each pair matches the input value. If a match is found, the corresponding key is returned.

The main function creates a HashMap and inserts three key-value pairs into it. It then calls get_key_by_value to retrieve the key associated with the value "two" and prints the result.

Post a Comment