热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

如何有效地从HashMap中查找和插入?

如何解决《如何有效地从HashMap中查找和插入?》经验,为你挑选了1个好方法。

我想做以下事情:

查找Vec某个键,并将其存储起来供以后使用.

如果它不存在,Vec则为该键创建一个空,但仍将其保留在变量中.

如何有效地做到这一点?当然我以为我可以使用match:

use std::collections::HashMap;

// This code doesn't compile.
let mut map = HashMap::new();
let key = "foo";
let values: &Vec = match map.get(key) {
    Some(v) => v,
    NOne=> {
        let default: Vec = Vec::new();
        map.insert(key, default);
        &default
    }
};

当我尝试它时,它给了我错误,如:

error[E0502]: cannot borrow `map` as mutable because it is also borrowed as immutable
  --> src/main.rs:11:13
   |
7  |     let values: &Vec = match map.get(key) {
   |                                     --- immutable borrow occurs here
...
11 |             map.insert(key, default);
   |             ^^^ mutable borrow occurs here
...
15 | }
   | - immutable borrow ends here

我最终做了类似的事情,但我不喜欢它执行两次查询(map.contains_keymap.get)的事实:

// This code does compile.
let mut map = HashMap::new();
let key = "foo";
if !map.contains_key(key) {
    let default: Vec = Vec::new();
    map.insert(key, default);
}
let values: &Vec = match map.get(key) {
    Some(v) => v,
    NOne=> {
        panic!("impossiburu!");
    }
};

只有一个安全的方法match吗?



1> huon..:

entryAPI是专为这一点.在手动形式,它可能看起来像

use std::collections::hash_map::Entry;

let values: &Vec = match map.entry(key) {
    Entry::Occupied(o) => o.into_mut(),
    Entry::Vacant(v) => v.insert(default)
};

或者可以使用简短的形式:

map.entry(key).or_insert_with(|| default)

default即使没有插入,如果计算好/便宜,它也可以是:

map.entry(key).or_insert(default)


entry()的问题是,你总是要克隆密钥,有没有办法避免这种情况?
推荐阅读
author-avatar
手机用户2502860901
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有