find the key associated with a value in a map in rust

You can use the get() method provided by the HashMap to get the value associated with a certain key. Here's an example:

main.rs
use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert("key1", 1);
    map.insert("key2", 2);
    map.insert("key3", 3);
    
    let search_value = 2;
    
    let search_key = map.iter().find_map(|(&key, &value)| {
        if value == search_value {
            Some(key)
        } else {
            None
        }
    });
    
    match search_key {
        Some(key) => println!("The key {} is associated with the value {}", key, search_value),
        None => println!("No key found for the value {}", search_value),
    }
}
569 chars
24 lines

In this example, we create a new HashMap and insert three key-value pairs into it. Then, we define a search_value variable, which is the value we want to find the key for. We use the iter() method to iterate over all the key-value pairs in the map. For each pair, we check if the value matches our search_value. If it does, we return the key as a Some value. If it doesn't, we return None. We use the find_map() method to find the first key for which our closure returns a Some value. Finally, we print out the result.

related categories

gistlibby LogSnag