Implement Ord to compare different types

Why is it not possible to implement Ord for a different Rhs type? It is possible with PartialOrd, so I assume it has something to do with the difference between the two? Is it because different types should not have a total ordering defined between each other? If so, why not?

I don't know the original reason, but the default implementations of Ord::{min,max} (Rust 1.21) and Ord::clamp (Rust 1.50) can only work with Self arguments for comparison.

So it sounds like more of an oversight, right? Because I can't see a reason why that should be prohibited..

Is it possible to amend the trait definition in this way, with a type parameter defaulting to Self, while remaining backwards compatible?

I believe it's because implementing Ord requires also implementing Eq, which doesn't have an Rhs type parameter to ensure symmetry (a == b implies b == a)

I sketched out some history as best as I could tell here.

4 Likes

But symmetry could be ensured even with something like this, on the type level at least:

trait Eq<Rhs = Self>
    where Rhs: Eq<Self> + ?Sized
{
    fn eq(&self, other: &Rhs) -> bool;
}

(test)

So its not an oversight, but just hasn't been implemented yet, if I understand correctly.

Well, I doubt someone accidentally removed the generics in the stabilization PR, but I can't really speak for anyone else. It is technically a non-implemented [1] part of an accepted [2] RFC. I have no idea what the lib team would think about adding it today, or if they'd care that it's technically accepted after over 7 years of it being removed.

As it would be a change to the standard library, you could ask on IRLO.


  1. * no-longer implemented ↩︎

  2. but pre-1.0 ↩︎

2 Likes

Thank you for clarification