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

In Rust, you can use a HashMap to create a key-value store. To get the value associated with a key, you can use the HashMap::get function.

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

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

    // get the value associated with the key "one"
    match map.get("one") {
        Some(value) => println!("Value: {}", value),
        None => println!("Key not found"),
    }
}
341 chars
15 lines

In the code block above, we first create a new HashMap and insert key-value pairs. We then use the HashMap::get function to retrieve the value associated with "one". The function returns an Option, which we then match on to check if the key was found. If the key was found, we print the value. If not, we print a message saying that the key was not found.

related categories

gistlibby LogSnag