我想不出一种方法来将元素保存在HashMap
中并同时进行编辑:
use std::collections::HashMap;
#[derive(Clone, Debug)]
pub struct Alliance {
pub name: String,
pub id: u32,
}
fn main() {
let mut hashmap = HashMap::new();
let mut alliance1 = Alliance {
name: "alliance_1".to_string(),
id: 1,
};
let mut alliance2 = Alliance {
name: "alliance_2".to_string(),
id: 2,
};
// Do I really need to clone the name strings here?
let mut entry1 = hashmap.entry(alliance1.name.clone()).or_insert(alliance1);
let mut entry2 = hashmap.entry(alliance2.name.clone()).or_insert(alliance2);
swapNames(entry1, entry2);
println!("{}", entry1.name);
println!("{}", entry2.name);
}
fn swapNames(entry1: &mut Alliance, entry2: &mut Alliance) {
let aux = entry1.name.clone();
entry1.name = entry2.name.clone();
entry2.name = aux;
}
我得到一个我同意的错误:
error[E0499]: cannot borrow `hashmap` as mutable more than once at a time
--> src/main.rs:24:22
|
23 | let mut entry1 = hashmap.entry(alliance1.name.clone()).or_insert(alliance1);
| ------- first mutable borrow occurs here
24 | let mut entry2 = hashmap.entry(alliance2.name.clone()).or_insert(alliance2);
| ^^^^^^^ second mutable borrow occurs here
...
30 | }
| - first borrow ends here
我只是不知道如何以编译方式进行编码。我需要保持Alliance
结构可变,以便在代码中进一步对其进行编辑(swapNames
函数只是一个示例)。