我正在尝试将多个元素添加到HashMap
in a for
循环但似乎无法正确执行:
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 循环。
你的问题不在于你试图将元素添加到你的HashMap
在一个循环中,你正在修改你的哈希图and尝试访问您的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();
}
在此代码中,您正在访问哈希图after填满它也填满你的attendees
vector.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)