【问题标题】:How to look up values in a HashMap<Option<String>, V> without copying?如何在不复制的情况下查找 HashMap<Option<String>, V> 中的值?
【发布时间】:2021-02-19 16:35:29
【问题描述】:

我有一个HashMapOption&lt;String&gt; 键;是否可以使用Option&lt;&amp;str&gt; 类型的键进行查找?我知道我可以使用&amp;strHashMap&lt;String, V&gt; 中查找,因为str 实现了Borrow&lt;String&gt;

我是否必须转换为拥有的字符串才能进行查找?

【问题讨论】:

  • Entry api 用于选择性地向地图添加键,我只是在谈论查找。
  • 最后一次重复是关于答案而不是问题阅读答案不是问题*--
  • 使用原始入口api,我能想到的唯一解决方案是使用map.raw_entry().from_hash(somehow_calculate_a_hash(key), |k| k.as_ref() == key)
  • 在我链接到你的线程中没有写from_hash()。我无法为你阅读。

标签: rust hashmap optional


【解决方案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));
}

【讨论】:

    猜你喜欢
    • 2014-10-17
    • 2021-03-28
    • 1970-01-01
    • 2021-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多