英文:
Eq and PartialEq matching two unmatching types being equal
问题
我试图实现PartialEq
,用于两种不同类型,以使枚举A
的一个成员等于枚举B
的一个成员。
impl PartialEq for A {
fn eq(&self, other: &B) -> bool {
match (self, other) {
...
}
}
}
但是,我收到了错误消息:
改变参数类型以匹配trait:&EventType
如何完成这个操作?是否可以像Python的__eq__
一样重载以匹配任何两种随机类型?
英文:
I was trying to implement PartialEq
, for two different types, in a way that one member of enum A
is equal to one member of enum B
.
impl PartialEq for A {
fn eq(&self, other: &B) -> bool {
match (self, other) {
...
}
}
}
but, I got error:
change the parameter type to match the trait: `&EventType`
How can I get this done? is it even possible to overload like python __eq__
to match any two random types?
答案1
得分: 1
你可以实现与另一个 Rhs
的比较,但你必须显式提供该类型参数:
impl PartialEq<B> for A {
fn eq(&self, other: &B) -> bool {
match (self, other) {
//…
}
}
}
否则,它将使用 它的定义 中的 Self
的默认值:
pub trait PartialEq<Rhs = Self>
// …
英文:
You can implement comparision to another Rhs
but you have to explicitly provide that type parameter:
impl PartialEq<B> for A {
fn eq(&self, other: &B) -> bool {
match (self, other) {
//…
}
}
}
Or else it's using the default of Self
from it's definiton:
> ```rust
> pub trait PartialEq<Rhs = Self>
> // …
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论