我有一个带有 `Option` 键的 `HashMap`。是否可以使用类型为 `Option<&str>` 的键进行查找?我知道我可以在 `HashMap` 中使用 `&str` 进行查找,因为 `str` 实现了 `Borrow`。我需要先将其转换为拥有字符串吗才能进行查找呢?
虽然效率稍低,但在这里你可以使用 Cow
。它避免了使用 Borrow
特质时的问题,而是使用单一类型来表示引用或拥有的值,如下所示:
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));
}
map.raw_entry().from_hash(somehow_calculate_a_hash(key), |k| k.as_ref() == key)
。 - Twan van Laarhoven