我正在编写一个函数,它可以将值插入或更新到作为结构一部分的 HashMap 中。
我的 map 类型为 HashMap<String, Value>
其中 Value
是我程序中别处定义的枚举。我有一个函数 pub fn bind(&mut self, name: &str, value: Value)
在我的结构上,在 HashMap 中插入或更新条目,目前我的代码如下所示:
pub fn bind(&mut self, name: &str, value: Value) -> /* snip */ {
/* snip */
self.bindings.insert(name.to_string(), value);
/* snip */
}
这很好,如果 name
不在 hashmap 中,但如果在 hashmap 中,是否可以通过更新现有条目来避免 to_string 的开销,而不是调用 to_string 并为我们已有的字符串分配更多内存?我想做这样的事情:
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 */
}
最佳答案
您可以使用 HashMap::get_mut
获取对值(如果存在)的引用,这允许您修改它 - 特别是通过分配新值。
关于performance - 如何使用对键的引用更新 HashMap 中的条目?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68293899/