PartialOrd and Ord
Partial ordering & Total ordering.
Derivable: ✅
// Copyright 2025 Google LLC // SPDX-License-Identifier: Apache-2.0 #[derive(PartialEq, PartialOrd)] pub struct Partially(f32); #[derive(PartialEq, Eq, PartialOrd, Ord)] pub struct Totally { id: u32, name: String, } fn main() { let a = Totally { id: 0, name: "alice".into() }; let b = Totally { id: 1, name: "alice".into() }; let c = Totally { id: 0, name: "charlie".into() }; dbg!(a.cmp(&b)); dbg!(a.cmp(&c)); }
-
Comparison-related methods. If a type implements
PartialOrd/Ordthen you can use comparison operators (<,<=,>,>=) with that type. -
Ordgives access tomin,max, andclampmethods. -
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.