我手动为它定义了一个结构MyData
和实现PartialEq
和Hash
特征。
我定义了一个包含Rc<MyData>
and的枚举Rc<RefCell<MyData>>
。
我想为枚举派生PartialEq
和Hash
,但失败了:
PartialEq
和两者Hash
都适用于Rc<MyData>
;PartialEq
作品Rc<RefCell<MyData>>
也适用;- 但
Hash
不适用Rc<RefCell<MyData>>
!
我有两个问题:
为什么?为什么只有
Hash
不只适用于Rc<RefCell<MyData>>
?如何解决?
我无法实现
Hash
forRc<RefCell<MyData>>
。在四处搜索后,我找到了一种方法:定义一个新的包装器结构,likestruct 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)))
}
}