【发布时间】: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