Rust 如何在HashMap中查找值<;选项<;字符串>;,V>;不抄袭?
我有一个带有Rust 如何在HashMap中查找值<;选项<;字符串>;,V>;不抄袭?,rust,hashmap,optional,Rust,Hashmap,Optional,我有一个带有选项的HashMap;是否可以使用Option类型的键进行查找?我知道我可以使用&str在HashMap中查找,因为str实现了借用 我是否必须转换为一个拥有的字符串才能进行查找?效率稍低,但您可以在这里使用Cow。它避免了借用特性的问题,而是使用一个可以表示引用或拥有值的单一类型,如下所示: use std::borrow::Cow; use std::collections::HashMap; fn main() { let mut map = HashMap::<
选项的HashMap
;是否可以使用Option
类型的键进行查找?我知道我可以使用&str
在HashMap
中查找,因为str
实现了借用
我是否必须转换为一个拥有的字符串才能进行查找?效率稍低,但您可以在这里使用Cow
。它避免了借用
特性的问题,而是使用一个可以表示引用或拥有值的单一类型,如下所示:
use std::borrow::Cow;
use std::collections::HashMap;
fn main() {
let mut map = HashMap::<Option<Cow<'static, str>>, i32>::new();
map.insert(None, 5);
map.insert(Some(Cow::Borrowed("hello")), 10);
map.insert(Some(Cow::Borrowed("world")), 15);
// works with None and constant string slices...
assert_eq!(map.get(&None), Some(&5));
assert_eq!(map.get(&Some(Cow::Borrowed("hello"))), Some(&10));
// ...and also works with heap-allocated strings, without copies
let stack = String::from("world");
assert_eq!(map.get(&Some(Cow::Borrowed(&stack))), Some(&15));
}
使用std::borrow::Cow;
使用std::collections::HashMap;
fn main(){
让mut map=HashMap::这能回答您的问题吗?入口api用于选择性地向映射添加键,我只是在谈论查找。上次复制是关于答案而不是问题阅读答案而不是问题*——使用原始入口api,我能想到的唯一解决方案是使用map.raw_Entry()。from_hash(不知何故,|计算|a|hash(key),|k | k.as|u ref()==key)
。在我链接到您的线程中没有writefrom|hash()
。我无法为您阅读。