如何有效地查找和插入HashMap?我想做以下幾點(diǎn):查找aVec用于特定的密鑰,并將其存儲(chǔ)以供以后使用。如果不存在,則創(chuàng)建一個(gè)空Vec但仍然保留在變量中。如何有效地做到這一點(diǎn)?很自然,我想我可以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 }};當(dāng)我嘗試的時(shí)候,它給了我一些錯(cuò)誤,比如: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最后我做了這樣的事情,但我不喜歡它執(zhí)行兩次查找的事實(shí)(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!");
}};有一個(gè)安全的方法嗎?match?
如何有效地查找和插入HashMap?
白衣染霜花
2019-06-29 10:36:30