我正在编写一个函数,该函数可以将值插入或更新到结构中的 HashMap 中。我的 Map 的类型为 HashMap<String, Value>
,其中的 Value
是在我的程序中定义的枚举类型。我在我的结构体上有一个名为 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
这个键,那么这样做就没问题了,但是如果已经存在该键,是否有可能避免调用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 */
}