我是 Rust 新手,正在纠结为什么编译器对所有权的要求很严格。代码简化以专注于混淆。
fn some_fn() {
let mut a_map: HashMap<String, String> = HashMap::new();
loop {
match create_area(&a_map) {
-- pattern matching --
}
// This is the problem.
a_map.clear();
}
}
fn create_area(a_map: &HashMap<String, String>) -> Result {}
错误内容为:“不能将 a_map
借用为可变的,因为它也被借用为不可变的”
我的直觉是,因为我没有改变 a_map
的所有者,而且 create_area
不能改变 a_map
因为它具有的引用是不可变的,所以变异应该是“安全的”使用 a_map.clear()
。
将代码修改为以下内容以使其使用 clone 进行编译,还有其他方法吗?考虑到 a_map 可能非常大的情况。
fn some_fn() {
let mut a_map: HashMap<String, String> = HashMap::new();
loop {
match create_area(a_map.clone()) {
-- pattern matching --
}
a_map.clear();
}
}
fn create_area(a_map: HashMap<String, String>) -> Result {}