我有HashMap<String, Vec<String>>
。从向量中删除元素后,我想删除此向量的条目(如果它为空)。我试过这样做:
use std::collections::HashMap;
fn main() {
let mut map: HashMap<String, Vec<String>> = HashMap::new();
map.insert(String::from("key"), vec![String::from("value")]);
let a_key = String::from("key");
let del_from_vec = String::from("value");
match map.get_mut(&a_key) {
Some(vect) => match vect.binary_search(&del_from_vec.to_string()) {
Ok(index) => {
vect.remove(index);
println!("value removed from vector.");
if vect.len() == 0 {
map.remove(&a_key);
println!("entry removed from map.");
}
}
Err(_) => println!("not found in vec."),
},
None => println!("no such key in map."),
}
}
编译器抱怨这个:
error[E0499]: cannot borrow `map` as mutable more than once at a time
--> src/main.rs:17:21
|
11 | match map.get_mut(&a_key) {
| --- first mutable borrow occurs here
...
17 | map.remove(&a_key);
| ^^^ second mutable borrow occurs here
...
24 | }
| - first borrow ends here
我完全理解错误。我可以通过这样做来克服它:
use std::collections::HashMap;
fn main() {
let mut map: HashMap<String, Vec<String>> = HashMap::new();
map.insert(String::from("key"), vec![String::from("value")]);
let a_key = String::from("key");
let del_from_vec = String::from("value");
if map.contains_key(&a_key) {
match map[&a_key].binary_search(&del_from_vec.to_string()) {
Ok(index) => {
map.get_mut(&a_key).unwrap().remove(index);
println!("value removed from vector.");
if map[&a_key].len() == 0 {
map.remove(&a_key);
println!("entry removed from map.");
}
}
Err(_) => println!("not found in vec."),
}
}
}
我发现此代码很难看,因为它使用contains_key()
和unwrap()
。我怎么能写这个?