Best practice for retriving value from hashmap

⚓ Rust    📅 2026-05-03    👤 surdeus    👁️ 1      

surdeus

If I can guarantee that a value will exist in a HashMap for a specific key, such that either of the three options below will not panic, what would be the most idiomatic way of doing so?

    let mut example_map: HashMap<String, String> = HashMap::new();
    
    let key = String::from("Test_Key");
    let value = String::from("Test Value");

    example_map.insert(key.clone(), value);

    let foo = example_map[&key].clone();
    let bar = example_map.get(&key).unwrap().clone();
    let baz = example_map.get(&key).expect("failure message").clone();

3 posts - 3 participants

Read full topic

🏷️ Rust_feed