Trait for types that form a total order.
Implementations must be consistent with the [PartialOrd
] implementation, and ensure max
, min
, and clamp
are consistent with cmp
:
partial_cmp(a, b) == Some(cmp(a, b))
.max(a, b) == max_by(a, b, cmp)
(ensured by the default implementation).min(a, b) == min_by(a, b, cmp)
(ensured by the default implementation).- For
a.clamp(min, max)
, see the method docs (ensured by the default implementation).
It's easy to accidentally make cmp
and partial_cmp
disagree by deriving some of the traits and manually implementing others.
Violating these requirements is a logic error. The behavior resulting from a logic error is not specified, but users of the trait must ensure that such logic errors do not result in undefined behavior. This means that unsafe
code must not rely on the correctness of these methods.
Corollaries
From the above and the requirements of PartialOrd
, it follows that for all a
, b
and c
:
- exactly one of
a < b
,a == b
ora > b
is true; and <
is transitive:a < b
andb < c
impliesa < c
. The same must hold for both==
and>
.
Mathematically speaking, the <
operator defines a strict weak order. In cases where ==
conforms to mathematical equality, it also defines a strict total order.
Lexicographical comparison
Lexicographical comparison is an operation with the following properties:
- Two sequences are compared element by element.
- The first mismatching element defines which sequence is lexicographically less or greater than the other.
- If one sequence is a prefix of another, the shorter sequence is lexicographically less than the other.
- If two sequences have equivalent elements and are of the same length, then the sequences are lexicographically equal.
- An empty sequence is lexicographically less than any non-empty sequence.
- Two empty sequences are lexicographically equal.
How can I implement Ord
?
Ord
requires that the type also be [PARTIAL_RD
] and [EQ
] (which requires [PARTIAL_EQ
]).
Then you must define an implementation for [CMP
]. You may find it useful to use [CMP
] on your type's fields.
Methods
Compare two values.
Examples
use Ordering;
assert_eq!;
assert_eq!;
assert_eq!;
Return the minimum of two values.
Examples
assert_eq!;
assert_eq!;
assert_eq!;