find the values of a map in rust

To find the values of a HashMap in Rust, you can use the get method provided by the standard library. This method takes a key as an argument and returns an Option<&V>, where V is the type of values stored in the map. If the map contains the key, get returns Some(&V) with a reference to the value, otherwise it returns None.

Here's an example code snippet that shows how to find the values in a HashMap:

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

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

// Check if the map contains a key
if map.contains_key("two") {
    // Retrieve the value associated with key 'two'
    let value = map.get("two").unwrap();
    println!("Value of 'two' is {}", value);
} else {
    println!("Key 'two' not found in the map");
}
392 chars
16 lines

In this example, we create a HashMap, insert some key-value pairs, and then check if the key "two" exists in the map using the contains_key method. If the key exists, we retrieve the associated value using the get method and unwrap the Option using unwrap method to get the actual value. Finally, we print the value to the console.

gistlibby LogSnag