Rafael
Rafael

Reputation: 392

How can I update an entry in a HashMap with a refrence to a key?

I am writing a function which may insert or update a value into a HashMap that is part of a structure. My map is of type HashMap<String, Value> where Value is an enum defined elsewhere in my program. I have a function pub fn bind(&mut self, name: &str, value: Value) on my structure, that inserts or updates an entry in the HashMap, currently my code looks like this:

pub fn bind(&mut self, name: &str, value: Value) -> /* snip */ {
        /* snip */

        self.bindings.insert(name.to_string(), value);

        /* snip */    
}

This is fine if name was not already in the hashmap, but if it was, would it be possible to avoid the overhead of to_string by updating the existing entry, instead of calling to_string and allocating more memory for a string that we already have? I'm looking to do something like this:

pub fn bind(&mut self, name: &str, value: Value) -> /* snip */ {
        /* snip */

        if (self.bindings.contains(name)) {
                // this update method does not exist
                self.bindings.update(name, value);
        } else {
                self.bindings.insert(name.to_string(), value);
        }        
        
        /* snip */    
}

Upvotes: 3

Views: 1141

Answers (1)

apilat
apilat

Reputation: 1510

You can use HashMap::get_mut to get a reference to the value if it exists, which allows you to modify it - in particular by assigning a new value.

Playground

Upvotes: 2

Related Questions