【发布时间】:2021-10-13 15:01:00
【问题描述】:
我定义了一个结构 MyData 并为它手动实现 PartialEq 和 Hash 特征。
我定义了一个枚举,其中包括Rc<MyData> 和Rc<RefCell<MyData>>。
我想为枚举派生PartialEq 和Hash,但失败了:
-
PartialEq和Hash都适用于Rc<MyData>; -
PartialEq也适用于Rc<RefCell<MyData>>; - 但
Hash不适用于Rc<RefCell<MyData>>!
我有两个问题:
-
为什么?为什么只有
Hash不适用于Rc<RefCell<MyData>>? -
如何解决?
我无法为
Rc<RefCell<MyData>>实现Hash。在四处寻找之后,我找到了一种方法:定义一个新的包装结构,比如struct RRWrapper<T> (Rc<RefCell<T>>),然后为此RRWrapper实现Hash。但这会带来很多代码。有没有惯用的方法?我认为这是一般用法。
提前致谢,
吴
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)))
}
}
【问题讨论】:
-
您正在努力为您的枚举派生
Hash,但手动实现它应该没有问题。但正如@Netwave 所说,使具有内部可变性的对象可散列不一定是一个好主意。
标签: rust hash enums traits refcell