Why `sort()` need `T` to be `Ord`?

I don't think it's a good idea for your PartialOrd and Ord implementations to behave differently. In particular, you are actually violating Ord's invariants:

Implementations must be consistent with the PartialOrd implementation, and ensure max , min , and clamp are consistent with cmp :

  • partial_cmp(a, b) == Some(cmp(a, b)) .
  • max(a, b) == max_by(a, b, cmp) (ensured by the default implementation).
  • min(a, b) == min_by(a, b, cmp) (ensured by the default implementation).
  • For a.clamp(min, max) , see the method docs (ensured by the default implementation).

Normally if your type implements both, you'll implement one in terms of the other.

struct Foo { ... }

impl Ord for Foo {
  fn cmp(&self, other: &Self) -> Ordering { ... }
}

impl PartialOrd for Foo {
  fn partial_cmp(&self, other: &Self) -> Option<Ordering> { Some(self.cmp(other)) }
}

If you want your sorting to be reversed, then provide your own comparison which explicitly reverses the ordering - slice.sort_by(|a, b| b.cmp(a)).

1 Like