我想做以下几件事:
- 在
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
}
};
当我try 时,它会给我以下错误:
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!");
}
};
有没有一种安全的方法可以只用一个match
?