I am trying to add multiple elements to a HashMap
in a for
loop but can't seem to get it right:
use std::collections::HashMap;
fn set_if_needed_and_get(hmap: &mut HashMap<String, String>, st: String) -> &String {
hmap.entry(st.clone()).or_insert(st.clone())
}
fn main() {
let meeting_one_email = ["email1", "email2", "email1"];
let mut hmap: HashMap<String, String> = HashMap::new();
let mut attendees: std::vec::Vec<&String> = std::vec::Vec::new();
for m in meeting_one_email.iter() {
attendees.push(set_if_needed_and_get(&mut hmap, m.to_string()));
}
}
I get the error:
error[E0499]: cannot borrow `hmap` as mutable more than once at a time
--> src/main.rs:14:51
|
14 | attendees.push(set_if_needed_and_get(&mut hmap, m.to_string()));
| ^^^^ mutable borrow starts here in previous iteration of loop
15 | }
16 | }
| - mutable borrow ends here
I understand that I cannot borrow hmap
as mutable more than once, so how can I solve this while still using a for loop? Using a set and inserting in batches would work, but I want to use a for loop.