rust - 为什么 hash_map::Entry::or_insert_with 不能访问条目的键?
问题描述
我正在尝试有效地查找或插入一个项目到HashMap
同时拥有它的键和值的项目中。
根据如何有效地查找并插入 HashMap?, Entry
API 就是这样做的方法。
但是,在插入新项目时,我还需要访问密钥。
由于HashMap::entry
消耗了密钥,我无法执行以下操作,失败并显示error[E0382]: borrow of moved value: 'index'
:
let mut map: HashMap<String, Schema> = ...;
let index: String = ...;
let schema = map
.entry(index)
.or_insert_with(|| Schema::new(&index));
最简单的方法似乎如下:
let schema = match map.entry(index) {
Entry::Occupied(e) => e.into_mut(),
Entry::Vacant(e) => {
// VacantEntry::insert consumes `self`,
// so we need to clone:
let index = e.key().to_owned();
e.insert(Schema::new(&index))
}
};
如果只or_insert_with
将 传递Entry
给它调用的闭包,就可以像这样编写上面的代码:
let schema = map
.entry(index)
.or_insert_with_entry(|e| {
let index = e.key().to_owned();
Schema::new(&index)
});
我忽略了什么吗?编写此代码的最佳方法是什么?
解决方案
推荐阅读
- java - 如何使 JTable 中的单元格为空直到被点击?
- javascript - 比较 Javascript Ajax 响应与字符串
- javascript - “document.forms.value”-在 Microsoft Edge 中未定义
- typescript - Angular 6 - 如何以正确的方式从另一个异步函数中的异步函数回调中获取价值?
- ios - 如何检查整数值是否为 0 或因为它为空,所以将其值设为 0
- jquery - 如何读取选定的行(tr)列(td)数据属性
- mysql - 在动态数据透视表上添加另一列并计算 null/0 值
- macos - macOS Mojave 使用哪个链接器
- c++ - 使用具有外部依赖关系的库构建多个子项目
- c# - 如何使用身份 aspnetusers