简体   繁体   English

如何迭代 HashMap 的键并修改 HashMap 本身?

[英]How can I iterate over keys of a HashMap and modify the HashMap itself?

This is what I'm doing:这就是我正在做的事情:

struct Foo {
  m: HashMap<u32, String>
}
fn f(foo: &mut Foo) {
  let keys = Vec::new();
  for k in foo.m
    .into_iter()
    .filter(|(k, v)| v > 1)
    .map(|(k, v)| v) { keys.push(k); }
  for k in keys {
    let v = &foo.m.get(k)?;
    // now I do something with v, which in real
    // application is a struct and I will modify it here
  }
}

However, it says something along these lines:但是,它说明了以下内容:

error[E0382]: borrow of moved value: `foo.m`
   --> src/foo.rs:56:24
    |
50  |             .into_iter()
    |              ----------- `foo.m` moved due to this method call
...
56  |             let v = &foo.m.get(k)?;
    |                     ^^^^^^^^^^^^ value borrowed here after move

Basically, I'm trying to take the list of necessary keys and copy this list somewhere.基本上,我正在尝试获取必要键的列表并将此列表复制到某处。 Then, iterate over this new already copied list.然后,遍历这个新的已经复制的列表。 What am I doing wrong?我究竟做错了什么?

You're probably looking for iter_mut .您可能正在寻找iter_mut It allows you to iterate over the entries and modify their values.它允许您遍历条目并修改它们的值。

Looking at your original implementation, it seems like you only want to modify certain entries and leave others as-is, which is something that can be easily achieved with a guard clause during iteration.查看您的原始实现,您似乎只想修改某些条目而让其他条目保持原样,这可以通过迭代期间的保护子句轻松实现。

If you want your modified map to also only contain these particular keys, you should consume the full original map using into_iter and filter_map , then collect the tuples into a new map.如果您希望修改后的 map 也仅包含这些特定键,则应使用into_iterfilter_map使用完整的原始 map,然后将元组收集到新的 Z1D78DC8ED51214E518B5114AE249 中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM