在循环的每一次迭代中,我都想借用一个散列映射。
我有以下的散列映射、函数和循环:
use std::collections::HashMap;
fn func<'a>(hash_map: &'a mut HashMap<&'a str, String>) {
unimplimented!();
}
fn loop() {
let mut hash_map = HashMap::new();
let mut i = 0;
while i < 10 {
func(&mut hash_map);
i += 1;
}
}
这将在func(&mut hash_map);
行上产生以下错误:
cannot borrow `hash_map` as mutable more than once at a time
`hash_map` was mutably borrowed here in the previous iteration of the looprustc(E0499)
main.rs(62, 25): `hash_map` was mutably borrowed here in the previous iteration of the loop
,我如何重构它,以便能够在循环的每一次迭代中不断地借用哈希映射?
我相信我对Rust的所有权规则有足够的理解,足以理解为什么会发生这个错误,只是不足以修复它。
注意:我知道有更好的方法来用Rust编写一个循环,只是想要一个非常简单的循环。
发布于 2022-06-13 17:29:11
看起来我在函数参数类型定义中使用了不需要的生命周期。而不是hash_map: &'a mut HashMap<&'a str, String>
,我只需要使用hash_map: &mut HashMap<&'a str, String>
。
下面的代码适用于我。
use std::collections::HashMap;
use external::func;
fn func<'a>(hash_map: &mut HashMap<&'a str, String>) {
unimplimented!();
}
fn loop() {
let mut hash_map = HashMap::new();
let mut i = 0;
while i < 10 {
func(&mut hash_map);
i += 1;
}
}
https://stackoverflow.com/questions/72606657
复制相似问题