PartialOrd and Ord
Partial ordering & Total ordering.
Derivable: ✅
When to implement: Almost always.
#![allow(unused)] fn main() { // pub trait PartialOrd<Rhs = Self>: PartialEq<Rhs> // { // // Required method // fn partial_cmp(&self, other: &Rhs) -> Option<Ordering>; // // /* Provided methods omitted */ // } // pub trait Ord: Eq + PartialOrd { // // Required method // fn cmp(&self, other: &Self) -> Ordering; // // /* Provided methods omitted */ // } #[derive(PartialEq, PartialOrd)] pub struct Partially(f32); #[derive(PartialEq, Eq, PartialOrd, Ord)] pub struct Totally { id: u32, name: String, } }
Ord gives access to min, max, and clamp methods.
-
When derived, compares things in the order they are defined.
For enums this means each variant is considered “greater than” the last as they are written.
For structs this means fields are compared as they are written, so
idfields are compared beforenamefields inTotally. -
Prerequisites:
PartialEqforPartialOrd,EqforOrd.To implement
Ord, a type must also implementPartialEq,Eq, andPartialOrd. -
Like with
PartialEqandEq, a type cannot implementOrdwithout implementingPartialOrd.Like those equality traits,
PartialOrdexists to separate types with non-total ordering (particularly floating-point numbers) from types with total ordering. -
Used for sorting/searching algorithms and maintaining the ordering of
BTreeMap/BTreeSetstyle data types.