4

I want to implement a KeyValuePair<K, V> data structure that implements Ord if K implements Ord. Currently, this is my implementation:

use std::cmp::Ordering;

struct KeyValuePair<K, V> {
    key: K,
    value: V,
}

impl<K: PartialEq, V> PartialEq for KeyValuePair<K, V> {
    fn eq(&self, other: &Self) -> bool {
        self.key.eq(&other.key)
    }
}

impl<K: Eq, V> Eq for KeyValuePair<K, V> {}

impl<K: PartialOrd, V> PartialOrd for KeyValuePair<K, V> {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        self.key.partial_cmp(&other.key)
    }
}

impl<K: Ord, V> Ord for KeyValuePair<K, V> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.key.cmp(&other.key)
    }
}

Other than Ord, I also have to implement PartialEq, Eq and PartialOrd, which is a bit too much. I don’t want to use #[derive] because that will compare value as well.

So is there any way I can simplify my code?

EFanZh
  • 2,357
  • 3
  • 30
  • 63
  • 2
    Possible duplicate of [Is it possible to create a macro that implements Ord by delegating to a struct member?](https://stackoverflow.com/questions/45664392/is-it-possible-to-create-a-macro-that-implements-ord-by-delegating-to-a-struct-m) – Stargateur May 02 '19 at 05:17
  • 2
    what do you want simplify ? There is 3 lines of code – Stargateur May 02 '19 at 05:18
  • you can do `Some(self.cmp(other))` in `PartialOrd` – Stargateur May 02 '19 at 05:22
  • @Stargateur I can’t use `Some(self.cmp(other))` in `PartialOrd` because I only constrain `K` to be `PartialOrd`, not `Ord`, and `PartialOrd` doesn’t have `cmp`. – EFanZh May 02 '19 at 06:41
  • @Stargateur The linked solution uses macros, which doesn’t reduce the code size because it still do 4 trait implementations in the macro definition. – EFanZh May 02 '19 at 06:46
  • Yes, that the point, there is nothing to simplify. – Stargateur May 02 '19 at 10:22

0 Answers0