3

我想构建一个哈希图,它们的键是引用。我希望这些引用的相等意味着引用相等,即两个引用借用同一个对象。

use std::collections::hash_map::HashMap;

struct SomeKey();
struct SomeValue();

fn main() {
    let m = HashMap::<&SomeKey, SomeValue>::new();
    
    let t = SomeKey();
    m.get(&t);
}

不幸的是,这失败了,编译器告诉我&SomeKey没有实现Hash/ Eq

error[E0599]: the method `get` exists for struct `HashMap<&SomeKey, SomeValue>`, but its trait bounds were not satisfied
  --> src/main.rs:10:7
   |
10 |     m.get(&t);
   |       ^^^ method cannot be called on `HashMap<&SomeKey, SomeValue>` due to unsatisfied trait bounds
   |
   = note: the following trait bounds were not satisfied:
           `&SomeKey: Eq`
           `&SomeKey: Hash`

(操场)

我注意到,如果我实现Eq+Hashfor SomeKey,那么它可以工作,但这可能会使用底层对象相等,这不是我想要的。

有没有一种方法可以基于指针相等性将引用用作哈希映射键?

4

2 回答 2

4

你可以使用by_addresscrate。它包装任何指针/引用类型以按地址而不是按内容比较对象。

use std::collections::hash_map::HashMap;

use by_address::ByAddress;

struct SomeKey();
struct SomeValue();

fn main() {
    let mut m = HashMap::<ByAddress<&SomeKey>, SomeValue>::new();

    let t1 = SomeKey();
    let t2 = SomeKey();

    m.insert(ByAddress(&t1), SomeValue());
    assert!(m.get(&ByAddress(&t1)).is_some());
    assert!(m.get(&ByAddress(&t2)).is_none());
}
于 2021-09-24T01:45:22.870 回答
2

这可以通过在引用上实现Hash和处理Eq,然后使用函数 fromstd::ptr来执行操作。将引用转换为 ausize然后对它们进行操作也可以。您只需要确保在impls 中取消引用一次,因为&Self它的类型为&&SomeKey.

use std::collections::HashMap;

struct SomeKey();
struct SomeValue();
impl<'a> PartialEq for &'a SomeKey{
    fn eq(&self, other:&Self) -> bool{
        std::ptr::eq(*self, *other)
    }
}
impl<'a> Eq for &'a SomeKey{}
use std::hash::Hash;
use std::hash::Hasher;
impl<'a> Hash for &'a SomeKey {
    fn hash<H: Hasher>(&self, state: &mut H) {
        std::ptr::hash(*self, state)
    }
}


fn main() {
    let m = HashMap::<&SomeKey, SomeValue>::new();
    
    let t = SomeKey();
    m.get(&&t);
}

操场。

于 2021-09-24T03:20:23.100 回答