[Solved] How to define PartialEq for different types?


I defined a type of my own, Decimal. I could successfully define PartialEq for this struct. However, as Decimal is the representation of a number I want to compare it to i32, u32, i64, u64 and the floating decimals. I have no idea how to approach that as I cannot find any docs on comparing different types.

I am reading the community book (which I bought on paper … :slight_smile: ) and I did search the web.

Maybe I am just looking in the wrong place. Pointers, anyone? Or is this just impossible?


AFAIO, Eq and Ord are intently designed to compare two sides of the same type. While PartialEq and PartialOrd allow for generics, defining implementation of

PartialEq <RightHandType>

(answer corrected, thanks to hashedone)


You may define PartialEq to comparing with any type: https://doc.rust-lang.org/std/cmp/trait.PartialEq.html.

impl std::cmp::PartialEq<u32> for Decimal {
  fn eq(&self, other: &u32) -> bool { /* ... */ }

If you want to impl PartialEq for all numeric types at once, the most principled approach is probably create macro implementing your PartialEq and call it for every type (I’ve seen this in Rust stdlib afair).


Thank you very much! I will be attempting this approach. Maybe I can use a generic approach using a trait to separate numbers from the rest. Thanks!