rust - 如何删除满足条件的 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
解决方案
错误是由键和值被借用的事实引起的。答案是在调用之前复制它们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)
}
如果删除条目后不需要该值,则只需要密钥的副本。
推荐阅读
- javascript - 使用实时可发布密钥时不生成条带令牌
- html - 我可以让固定文本在横幅之后消失吗?
- java - Spring Boot for Kafka - 一个应用程序中的多个 KafkaStreams 配置
- vuex - Vuex 变量正确更新但未在模板中刷新
- reactjs - 单击任何链接时如何关闭侧边栏?
- c++ - 在 BinomialHeap 实现中使用 union(x, y) 中的删除
- node.js - 运行服务器时 Heroku 抛出错误
- r - 与 R 中的 2 个或更多自由度对比
- ruby-on-rails - Rails 为外部资源的所有成员嵌套资源
- python - ModuleNotFoundError:没有名为“pynput”的模块,即使它已被明确下载