问题描述
是否可以使用Entry
API 通过 AsRef
获取值,但使用 Into
插入?
Is it possible to use the Entry
API to get a value by a AsRef<str>
, but inserting it with Into<String>
?
这是工作示例:
use std::collections::hash_map::{Entry, HashMap};
struct Foo;
#[derive(Default)]
struct Map {
map: HashMap<String, Foo>,
}
impl Map {
fn get(&self, key: impl AsRef<str>) -> &Foo {
self.map.get(key.as_ref()).unwrap()
}
fn create(&mut self, key: impl Into<String>) -> &mut Foo {
match self.map.entry(key.into()) {
Entry::Vacant(entry) => entry.insert(Foo {}),
_ => panic!(),
}
}
fn get_or_create(&mut self, key: impl Into<String>) -> &mut Foo {
match self.map.entry(key.into()) {
Entry::Vacant(entry) => entry.insert(Foo {}),
Entry::Occupied(entry) => entry.into_mut(),
}
}
}
fn main() {
let mut map = Map::default();
map.get_or_create("bar");
map.get_or_create("bar");
assert_eq!(map.map.len(), 1);
}
我的问题是在 get_or_create
中总是会创建一个 String
,从而导致不需要的内存分配,即使它不是被占用的条目所需要的.有没有可能以任何方式解决这个问题?也许以一种巧妙的方式使用 Cow
?
My problem is that in get_or_create
a String
will always be created, incurring unneeded memory allocation, even if it's not needed for an occupied entry. Is it possible to fix this in any way? Maybe in a neat way with Cow
?
推荐答案
在 nightly Rust 中,你可以使用不稳定的 raw_entry_mut()
允许这样做的功能:
In nightly Rust, you can use the unstable raw_entry_mut()
feature that allows this:
为 HashMap 创建一个原始条目构建器.
[...]
原始条目对于以下奇特情况很有用:
Raw entries are useful for such exotic situations as:
- 推迟创建自有密钥,直到知道需要它
在稳定的 Rust 中,您可以添加 hashbrown 板条箱,它具有相同的 API 但稳定.hashbrown crate实际上是标准库hashmap的底层实现.
In stable Rust, you can add the hashbrown crate which has the same API but stable. The hashbrown crate is actually the underlying implementation of the standard library's hashmap.
示例:
#![feature(hash_raw_entry)]
use std::collections::HashMap;
#[derive(Hash, PartialEq, Eq, Debug)]
struct NoCopy {
foo: i32,
}
impl Clone for NoCopy {
fn clone(&self) -> Self {
println!("Clone of: {:?}", self);
Self { foo: self.foo }
}
}
fn main() {
let no_copy = NoCopy { foo: 21 };
let mut map = HashMap::new();
map.raw_entry_mut()
.from_key(&no_copy)
.or_insert_with(|| (no_copy.clone(), 42));
map.raw_entry_mut()
.from_key(&no_copy)
.or_insert_with(|| (no_copy.clone(), 84));
println!("{:#?}", map);
}
应用于您的原始示例:
fn get_or_create<K>(&mut self, key: K) -> &mut Foo
where
K: AsRef<str> + Into<String>,
{
self.map
.raw_entry_mut()
.from_key(key.as_ref())
.or_insert_with(|| (key.into(), Foo))
.1
}
这篇关于如何将 Entry API 与仅在 Entry 为空时才构造的昂贵密钥一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!