Derive Macro address_cmp::AddressOrd[][src]

#[derive(AddressOrd)]
Expand description

Derives PartialOrd and Ord based on memory addresses.

By deriving AddressOrd, the PartialOrd and Ord traits will automatically be implemented for the given type. The implementations will use a given instance’s address in memory in when performing comparison.

This form of comparison can be useful in certain cases, like implementing ordering based on position in a slice, but can also produce unexpected results depending on how the compiler chooses to place data in memory.

Since implementing PartialOrd on a type requires that the type also implements PartialEq and implementations of Hash and Eq must agree, it is recommended to derive both AddressOrd and AddressEq together.

use address_cmp::{AddressEq, AddressOrd};

#[derive(AddressEq, AddressOrd, Debug)]
struct Person {
    pub age: u8,
    pub name: String,
}

let p1 = Person { age: 22, name: "Mercutio".into() };
let p2 = Person { age: 22, name: "Mercutio".into() };
let p3 = Person { age: 21, name: "Benvolio".into() };

let friends = vec![p1, p2, p3];

assert!(friends[0] < friends[1]);
assert!(friends[1] < friends[2]);
assert_eq!(friends[0], friends[0]);