【问题标题】:Adding entries to a HashMap and getting references to them in a for loop向 HashMap 添加条目并在 for 循环中获取对它们的引用
【发布时间】:2018-01-23 06:17:16
【问题描述】:

我正在尝试在 for 循环中向 HashMap 添加多个元素,但似乎无法正确处理:

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()));
    }
}

我得到错误:

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

我知道我不能多次借用 hmap 作为 mutable,那么在仍然使用 for 循环的同时如何解决这个问题?使用集合并分批插入可以,但我想使用 for 循环。

【问题讨论】:

  • 如果你能做到这一点,你可能会在attendees数组中得到一堆无效的引用。 HashMap 可以重新分配其存储空间。
  • 简短回答:你不能(存储引用,然后通过改变容器使它们无效)。

标签: rust


【解决方案1】:

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

由于您在 hmap 上有一个可变借用,因此您不能在循环中将其元素推送到您的 attendees 向量。向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();
}

在此代码中,您正在访问散列图填充它以填充您的attendees 向量。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多