PartialCmp

Derive Macro PartialCmp 

Source
#[derive(PartialCmp)]
{
    // Attributes available to this derive:
    #[ord]
}
Expand description

Derives comparison and hash traits with customizable field behavior.

By default, this macro generates implementations for PartialEq, Eq, PartialOrd, Ord, and Hash. All traits respect the same field configuration, ensuring consistent behavior.

§Struct-Level Attributes

  • #[ord(reverse)] — Reverses the final comparison result
  • #[ord(by = [field1(asc), field2(desc)])] — Explicit field comparison order
  • #[ord(skip_partial_eq)] — Don’t generate PartialEq (disables all other traits too)
  • #[ord(skip_eq)] — Don’t generate Eq (also disables Ord)
  • #[ord(skip_partial_ord)] — Don’t generate PartialOrd (also disables Ord)
  • #[ord(skip_ord)] — Don’t generate Ord
  • #[ord(skip_hash)] — Don’t generate Hash

§Field-Level Attributes

  • #[ord(skip)] — Exclude this field from all comparisons and hashing
  • #[ord(order = "asc")] or #[ord(order = "desc")] — Sort direction
  • #[ord(priority = N)] — Comparison priority (lower = compared first)
  • #[ord(key = "path::to::fn")] — Key extraction function (signature: fn(&T) -> U)
  • #[ord(none_order = "first")] or #[ord(none_order = "last")] — Option handling

§Variant-Level Attributes (Enums)

  • #[ord(rank = N)] — Explicit variant ranking (lower = less than)

§Key Extraction

The key attribute specifies a function that extracts a comparable/hashable value from a field. The extracted key is used consistently for Eq, Ord, and Hash, ensuring the invariant a == b -> hash(a) == hash(b) is maintained.

use partial_cmp_derive::PartialCmp;

fn abs_key(v: &i32) -> i32 {
    v.abs()
}

#[derive(Debug, PartialCmp)]
struct AbsValue {
    #[ord(key = "abs_key")]
    value: i32,
}

let a = AbsValue { value: -5 };
let b = AbsValue { value: 5 };

assert_eq!(a, b);  // Equal because abs(-5) == abs(5)

§Example

use partial_cmp_derive::PartialCmp;

#[derive(Debug, PartialCmp)]
#[ord(by = [score(desc), name(asc)])]
struct Player {
    id: u64,      // Not compared (not in `by` list)
    name: String,
    score: u32,
}