首页 > 解决方案 > 为什么 hash_map::Entry::or_insert_with 不能访问条目的键?

问题描述

我正在尝试有效地查找或插入一个项目到HashMap同时拥有它的键和值的项目中。

根据如何有效地查找并插入 HashMap?, EntryAPI 就是这样做的方法。

但是,在插入新项目时,我还需要访问密钥。

由于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)
    });

我忽略了什么吗?编写此代码的最佳方法是什么?

标签: rusthashmap

解决方案


推荐阅读