Я пытаюсь использовать функцию Iterator filter_map
с HashMap
в Rust, но я не могу ее скомпилировать. Предположим, у меня есть HashMap
и список ключей. Для каждого ключа, если карта содержит ключ, я мутирую соответствующее значение на карте. Например, предположим, что значения были типа i32
, и я хотел увеличить соответствующие значения.Пожизненные ошибки с использованием filter_map
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?
Я не вижу эффекта сглаживания. Мы производим mutable ссылки с get_mut, но сроки жизни этих ссылок не должны перекрываться, насколько я могу судить. Если я чего-то не упускаю, он следует той же логике, что и ваш код. – Iceberg