use std::collections::{HashMap, HashSet};
use std::hash::{Hash};
fn test(data: &mut HashMap<String, HashSet<String>>) {
match data.get("foo") {
None => return,
Some(xs) => {
let xs: Vec<String> = xs.iter().map(|x| x.to_owned()).collect();
// How to drop `data` here so that I can borrow `data`.
for x in xs {
// Mutable borrow occurs, because previous `data` is still in scope.
data.remove(&x);
}
}
}
}
上面的代码不起作用,因为我可变地再次借用data
,而之前的借用仍在范围内。但是,我找不到一种简单的方法来放弃先前借用的绑定。
此外,有没有更好的方法来复制xs
,以便我可以在迭代时修改hashmap。
答案 0 :(得分:2)
你非常接近解决方案。一旦你有了一个独立的向量,你可以将它从借用地图的范围中移出:
use std::collections::{HashMap, HashSet};
fn test(data: &mut HashMap<String, HashSet<String>>) {
let xs: Vec<String> = match data.get("foo") {
None => return,
Some(xs) => {
xs.iter().map(|x| x.to_owned()).collect()
}
};
for x in xs {
data.remove(&x);
}
}