rusthashmap

HashMap get or insert and return a reference from a function


I have the following code where I would like to return a reference from a HashMap (either get or insert a new value) and only do a single lookup. Is this possible in Rust?

Here is a playground link to play around with.

fn get(key: u32, map: &mut HashMap<u32, String>) -> &mut String {
    match map.entry(key) {
        Entry::Occupied(mut entry) => entry.get_mut(),
        Entry::Vacant(entry) => {
            entry.insert("Hello".into())
        }
    }
}

Solution

  • Do you want this?

    fn get(key: u32, map: &mut HashMap<u32, String>) -> &mut String {
        map.entry(key).or_insert_with(|| "Hello".into())
    }