Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

rust

As seen in How can an operator be overloaded for different RHS types and return values? you can implement some operators, eg. Add on multiple types using a work around.

Is a similar thing possible for the PartialEq trait?

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:

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.

Is there a way to do this?

like image 614
Doug Avatar asked Jul 17 '14 07:07

Doug


1 Answers

The == operator is only overridable via the PartialEq trait, and thus usable with matching types. Any other form of equality/equivalence needs a custom function/method, you can use the Equiv trait, although values that are equivalent should theoretically also have the same hash (or else HashMap.find_equiv won't work as you expect).

like image 81
huon Avatar answered Oct 17 '22 05:10

huon