如何在不复制的情况下查找HashMap<Option<String>, V>中的值?

4
我有一个带有 `Option` 键的 `HashMap`。是否可以使用类型为 `Option<&str>` 的键进行查找?我知道我可以在 `HashMap` 中使用 `&str` 进行查找,因为 `str` 实现了 `Borrow`。我需要先将其转换为拥有字符串吗才能进行查找呢?

Entry API 用于可选地向映射中添加键,我只是在谈论查找。 - Twan van Laarhoven
最后一次重复是关于答案而不是问题,请阅读答案而不是问题。*-- - Stargateur
使用原始输入API,我能想到的唯一解决方案是使用 map.raw_entry().from_hash(somehow_calculate_a_hash(key), |k| k.as_ref() == key) - Twan van Laarhoven
那个线程中没有直接回答我的问题。我认为你的意思是我应该像那个问题的被接受的回答所建议的那样使用raw_entry API。如果这不是你的意思,那么你的意思是什么? - Twan van Laarhoven
显示剩余2条评论
1个回答

1

虽然效率稍低,但在这里你可以使用 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));
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接