2

我手动为它定义了一个结构MyData和实现PartialEqHash特征。

我定义了一个包含Rc<MyData>and的枚举Rc<RefCell<MyData>>

我想为枚举派生PartialEqHash,但失败了:

  1. PartialEq和两者Hash都适用于Rc<MyData>;
  2. PartialEq作品Rc<RefCell<MyData>>也适用;
  3. Hash不适用Rc<RefCell<MyData>>

我有两个问题:

  1. 为什么?为什么只有Hash不只适用于Rc<RefCell<MyData>>

  2. 如何解决?

    我无法实现Hashfor Rc<RefCell<MyData>>。在四处搜索后,我找到了一种方法:定义一个新的包装器结构,like struct RRWrapper<T> (Rc<RefCell<T>>),然后Hash为此实现RRWrapper。但这会带来很多代码。有没有惯用的方法?我认为这是一个普遍的用法。

预先感谢,

PS:在我程序的真实代码中,只有Rc<RefCell<MyData>>枚举中没有Rc<MyData>. 我放在Rc<MyData>这里只是为了比较。PS2:在我程序的真实代码中,枚举中不止一个Rc<RefCell<T>>


原始源代码:

use std::rc::Rc;
use std::cell::RefCell;
use std::hash::{Hash, Hasher};

struct MyData {
    i: i64,
}

impl Hash for MyData {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.hash(state);
    }
}
impl PartialEq for MyData {
    fn eq(&self, other: &Self) -> bool {
        self == other
    }
}

#[derive(PartialEq, Hash)]
enum MyEnum {
    INT(i64),
    STR(String),
    MYDATA1(Rc<MyData>), // OK both
    MYDATA2(Rc<RefCell<MyData>>), // OK for PartialEq but not for Hash
}

fn main() {
}

错误:

20  | #[derive(PartialEq, Hash)]
    |                     ---- in this derive macro expansion
...
25  |     MYDATA2(Rc<RefCell<MyData>>), // OK for PartialEq but not for Hash
    |             ^^^^^^^^^^^^^^^^^^^ the trait `Hash` is not implemented for `RefCell<MyData>`
    |
    = note: required because of the requirements on the impl of `Hash` for `Rc<RefCell<MyData>>`
    = note: this error originates in the derive macro `Hash` (in Nightly builds, run with -Z macro-backtrace for more info)

源代码struct RRWrapper


#[derive(Debug, PartialEq, Eq)]
pub struct RRWrapper<T: Hash+PartialEq+Eq>(Rc<RefCell<T>>);

impl<T: Hash+PartialEq+Eq> Deref for RRWrapper<T> {
    type Target = Rc<RefCell<T>>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}
impl<T: Hash+PartialEq+Eq> Hash for RRWrapper<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.0.borrow().hash(state);
    }
}
impl<T: Hash+PartialEq+Eq> Clone for RRWrapper<T> {
    fn clone(&self) -> Self {
        RRWrapper(self.0.clone())
    }
}
impl<T: Hash+PartialEq+Eq> RRWrapper<T> {
    pub fn new(inner: T) -> Self {
        RRWrapper(Rc::new(RefCell::new(inner)))
    }
}
4

1 回答 1

4

为什么?为什么只有散列不适用于 Rc<RefCell>?

如果您考虑一下,那Hash不为RefCell. 既然它是对内部可变性的抽象,那么可能会改变的东西的哈希值是什么?一般来说,可变的东西不适合作为Hash对象工作。

如何解决?

和你一样。对你真正想要的负责。为包装器实现它。

于 2021-10-13T15:04:39.767 回答