我想做以下事情:
- 为某个键查找
Vec
,并将其存储以备后用。 - 如果它不存在,则为键创建一个空的
Vec
,但仍将其保存在变量中。
如何有效地做到这一点?自然地,我认为我可以使用 match
:
use std::collections::HashMap;
// This code doesn't compile.
let mut map = HashMap::new();
let key = "foo";
let values: &Vec<isize> = match map.get(key) {
Some(v) => v,
None => {
let default: Vec<isize> = Vec::new();
map.insert(key, default);
&default
}
};
当我尝试它时,它给了我如下错误:
error[E0502]: cannot borrow `map` as mutable because it is also borrowed as immutable
--> src/main.rs:11:13
|
7 | let values: &Vec<isize> = match map.get(key) {
| --- immutable borrow occurs here
...
11 | map.insert(key, default);
| ^^^ mutable borrow occurs here
...
15 | }
| - immutable borrow ends here
我最终做了这样的事情,但我不喜欢它执行两次查找的事实(map.contains_key
和 map.get
):
// This code does compile.
let mut map = HashMap::new();
let key = "foo";
if !map.contains_key(key) {
let default: Vec<isize> = Vec::new();
map.insert(key, default);
}
let values: &Vec<isize> = match map.get(key) {
Some(v) => v,
None => {
panic!("impossiburu!");
}
};
有没有一种安全的方法可以只用一个匹配
来做到这一点?
最佳答案
entry
API是为此而设计的。在手动形式下,它可能看起来像
let values = match map.entry(key) {
Entry::Occupied(o) => o.into_mut(),
Entry::Vacant(v) => v.insert(default),
};
可以通过 Entry::or_insert_with
使用简要表:
let values = map.entry(key).or_insert_with(|| default);
如果 default
已经被计算,或者即使没有插入它也可以计算/便宜,您可以使用 Entry::or_insert
:
let values = map.entry(key).or_insert(default);
如果 HashMap
的值实现了 Default
,您可以使用 Entry::or_default
,尽管您可能需要提供一些类型提示:
let values = map.entry(key).or_default();
关于hashmap - 如何有效地从 HashMap 中查找和插入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34957646/