Eq和PartialEq匹配两个不匹配的类型相等。

huangapple go评论63阅读模式
英文:

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&lt;B&gt; for A {
    fn eq(&amp;self, other: &amp;B) -&gt; bool {
        match (self, other) {
            //…
        }
    }
}

Or else it's using the default of Self from it's definiton:
> ```rust
> pub trait PartialEq<Rhs = Self>
> // …

huangapple
  • 本文由 发表于 2023年3月12日 07:20:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75710173.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定