如何删除符合条件的BTreeMap或HashMap的第一个元素?

时间:2019-04-14 17:51:53

标签: rust borrowing

我想根据有关该值的某些属性从有序哈希图中删除(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

1 个答案:

答案 0 :(得分: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)
}

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