简体   繁体   English

是否可以在Rust中为不同类型实现equals运算符?

[英]Is it possible to implement the equals operator for different types in Rust?

As seen in How can an operator be overloaded for different RHS types and return values? 操作符如何为不同的RHS类型和返回值重载? you can implement some operators, eg. 你可以实现一些运营商,例如。 Add on multiple types using a work around. 使用解决方法添加多种类型。

Is a similar thing possible for the PartialEq trait? 对于PartialEq特性,类似的事情是否可能?

I've tried various things, but the closest I can get is creating a fake trait Foo, implementing PartialEq on &Foo (since it's a trait you can't implement it on Foo) and then doing: 我尝试了各种各样的东西,但是我能得到的最接近的是创建一个假的特性Foo,在&Foo上实现PartialEq(因为它是一个你不能在Foo上实现它的特性)然后做:

let x:Bar = ...
let y:FooBar = ...
if &x as &Foo == &y as &Foo {
  ...
}

The Equiv trait looks like it should be used for this, but as far as I can tell, implementing Equiv doesn't have anything to do with the == operator. Equiv特性看起来应该用于此,但据我所知,实现Equiv与==运算符没有任何关系。

Is there a way to do this? 有没有办法做到这一点?

The == operator is only overridable via the PartialEq trait, and thus usable with matching types. ==运算符只能通过PartialEq特征PartialEq ,因此可用于匹配类型。 Any other form of equality/equivalence needs a custom function/method, you can use the Equiv trait, although values that are equiv alent should theoretically also have the same hash (or else HashMap.find_equiv won't work as you expect). 平等/等值的任何其他形式的需要自定义函数/方法,你可以使用Equiv特点,虽然是值equiv alent理论上应该也具有相同的哈希(或者HashMap.find_equiv像您期望的将无法正常工作)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM