将条目添加到 HashMap 并在 for 循环中获取对它们的引用 [英] Adding entries to a HashMap and getting references to them in a for loop

查看:65
本文介绍了将条目添加到 HashMap 并在 for 循环中获取对它们的引用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我收到错误:

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 借用为可变的,那么如何在仍然使用 for 循环的同时解决这个问题?使用集合并批量插入可以工作,但我想使用 for 循环.

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.

推荐答案

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

Your problem is not that you are trying to add elements to your HashMap in a loop, it's that you are modifying your hashmap and trying access your hmap in the scope of the loop.

因为您在 hmap 上有一个可变借用,所以您不能将其元素推送到循环中的 attendees 向量.将值添加到 HashMap 可能需要哈希映射重新分配自身,这会使对其内部值的任何引用无效.

As you have a mutable borrow on hmap, you are not allowed to push its elements to your attendees vector in the loop. Adding a value to the HashMap may require that the hashmap reallocate itself, which would invalidate any references to values inside it.

解决您问题的一个简单方法是:

One easy solution for your problem could be this:

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 向量.

In this code, you are accessing the hashmap after filling it up to also fill your attendees vector.

这篇关于将条目添加到 HashMap 并在 for 循环中获取对它们的引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆