首页 > 解决方案 > 如何删除满足条件的 BTreeMap 或 HashMap 的第一个元素?

问题描述

我想(key, value)根据有关值的某些属性从有序哈希图中删除 a 。

我写了以下最小示例:

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

标签: rustborrowing

解决方案


错误是由键和值被借用的事实引起的。答案是在调用之前复制它们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)
}

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


推荐阅读