I can't figure out a way to hold elements inside a HashMap
and edit them at the same time:
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;
}
I get an error which I agree with:
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
I just don't know how to code this in a way that compiles. I need to keep the Alliance
structs mutable to further edit them down in the code (the swapNames
function is just an example).