【发布时间】:2023-03-24 17:55:02
【问题描述】:
我正在尝试在 Rust 中使用 Iterator 的 filter_map 函数和 HashMap,但我无法编译它。假设我有一个HashMap 和一个键列表。对于每个键,如果映射包含键,我会改变映射中的相应值。例如,假设值是 i32 类型,我想增加适当的值。
use std::collections::HashMap;
fn increment(map: &mut HashMap<i32, i32>, keys: &[i32]) {
for value in keys.iter().filter_map(|index| map.get_mut(index)) {
*value += 1;
}
}
fn main() {
let mut map = HashMap::new();
map.insert(1,2);
map.insert(4,5);
increment(&mut map, &[0, 1, 2]);
assert!(*map.get(&1).unwrap() == 3);
assert!(*map.get(&4).unwrap() == 5);
}
这段代码给了我一个与生命周期相关的错误:
<anon>:4:57: 4:71 error: cannot infer an appropriate lifetime for autoref due to conflicting requirements
<anon>:4 for value in keys.iter().filter_map(|index| map.get_mut(index)) {
^~~~~~~~~~~~~~
<anon>:4:9: 6:10 note: in this expansion of for loop expansion
<anon>:4:9: 6:10 note: first, the lifetime cannot outlive the call at 4:8...
<anon>:4 for value in keys.iter().filter_map(|index| map.get_mut(index)) {
<anon>:5 *value += 1;
<anon>:6 }
<anon>:4:9: 6:10 note: in this expansion of for loop expansion
<anon>:4:9: 6:10 note: ...so that argument is valid for the call
<anon>:4 for value in keys.iter().filter_map(|index| map.get_mut(index)) {
<anon>:5 *value += 1;
<anon>:6 }
<anon>:4:9: 6:10 note: in this expansion of for loop expansion
<anon>:4:53: 4:71 note: but, the lifetime must be valid for the method call at 4:52...
<anon>:4 for value in keys.iter().filter_map(|index| map.get_mut(index)) {
^~~~~~~~~~~~~~~~~~
<anon>:4:9: 6:10 note: in this expansion of for loop expansion
<anon>:4:53: 4:56 note: ...so that method receiver is valid for the method call
<anon>:4 for value in keys.iter().filter_map(|index| map.get_mut(index)) {
^~~
<anon>:4:9: 6:10 note: in this expansion of for loop expansion
error: aborting due to previous error
为什么会出现这个错误,使用惯用的 Rust 处理这种情况的最佳方法是什么?
【问题讨论】: