将条目添加到HashMap并在for循环中获取对它们的引用

lc2*_*817 4 rust

我试图HashMapfor循环中添加多个元素,但似乎无法正确:

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()));
    }
}
Run Code Online (Sandbox Code Playgroud)

我收到错误:

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
Run Code Online (Sandbox Code Playgroud)

我知道我不能hmap多次借用可变性,所以如何在仍然使用for循环时解决这个问题?使用集合和批量插入可以工作,但我想使用for循环.

nyr*_*o_0 7

你的问题并不是你试图HashMap在循环中添加元素,而是你正在修改你的hashmap 尝试hmap在循环范围内访问你的.

当你有一个可变借用时hmap,你不允许attendees在循环中将它的元素推送到你的向量.向值添加值HashMap可能需要hashmap重新分配自身,这将使对其中的值的任何引用无效.

一个简单的解决方案可能是您的问题:

fn main() {
    let meeting_one_email = ["email1", "email2", "email1"];

    let mut hmap: HashMap<String, String> = HashMap::new();

    for m in meeting_one_email.iter() {
        set_if_needed_and_get(&mut hmap, m.to_string());
    }
    let attendees: Vec<&String> = hmap.keys().collect();
}
Run Code Online (Sandbox Code Playgroud)

在此代码中,您填充之后访问hashmap 以填充attendees向量.