我想构建一个哈希图,它们的键是引用。我希望这些引用的相等意味着引用相等,即两个引用借用同一个对象。
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+Hash
for SomeKey
,那么它可以工作,但这可能会使用底层对象相等,这不是我想要的。
有没有一种方法可以基于指针相等性将引用用作哈希映射键?