Is it possible to provide 'more specific' `PartialOrd` implementations for some `Struct` depending on which type parameters implement `PartialOrd`?

⚓ Rust    📅 2026-02-26    👤 surdeus    👁️ 2      

surdeus

I have an item class like so:

struct Item<First, Second> {
    first: First,
    second: Second,
}

I want to implement PartialOrd (and also Ord) for this class for lexicographical ordering. This, at the very least, requires First: PartialOrd:

impl<First, Second> PartialOrd for Item<First, Second>
    where First: PartialOrd
{
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.first.partial_cmp(other.first)
    }
}

However, if it's also the case that Second: PartialOrd, then I'd ideally like to use second as a discriminant(?) to pick between items with the same first. For instance, sorting some items might look like this:

[
  Item { first: "a", second: "a" },
  Item { first: "a", second: "b" },  // 'aa < ab'
  Item { first: "x", second: "k" },
  Item { first: "x", second: "z" },
  Item { first: "z", second: "z" },  // 'xk < xz < zz'
]

Is this possible in Rust?

My first approach was to add a separate implementation where First: PartialOrd, Second: PartialOrd, but this of course results in conflicting implementations. I've read that specialisation may be of help, but I was hoping for a non-Nightly solution.

3 posts - 3 participants

Read full topic

🏷️ Rust_feed