如何删除满足条件的BTreeMap或HashMap的第一个元素? [重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我想从有序的hashmap中删除(key, value),具体取决于有关该值的某些属性。

我写了以下最小的例子:

use std::collections::BTreeMap;

pub fn remove_if42(map: &mut BTreeMap<String, u32>) -> Option<u32> {
    // Get the first element (minimum) from the ordered hash
    let (key, value) = map.iter_mut().next()?;

    if *value == 42 {
        map.remove(key);
    }
    Some(*value)
}

我可以读取该值,但是当我要求删除密钥时,我收到了一个借用错误:

error[E0499]: cannot borrow `*map` as mutable more than once at a time
 --> src/lib.rs:8:9
  |
5 |     let (key, value) = map.iter_mut().next()?;
  |                        --- first mutable borrow occurs here
...
8 |         map.remove(key);
  |         ^^^        --- first borrow later used here
  |         |
  |         second mutable borrow occurs here
rust borrowing
1个回答
0
投票

错误是由键和值借用的事实引起的。答案是在调用remove()之前复制它们:

use std::collections::BTreeMap;

pub fn remove_if42(map: &mut BTreeMap<String, u32>) -> Option<u32> {
    // Get the first element from the ordered hash
    let (key, value) = map.iter_mut().next_back()?;

    let key_cpy: String = key.to_string();
    let value_cpy = *value;
    if *value == 42 {
        map.remove(&key_cpy);
    }
    Some(value_cpy)
}

如果您在删除条目后不需要该值,则只需要该密钥的副本。

© www.soinside.com 2019 - 2024. All rights reserved.