Skip to content

Commit 8b00a08

Browse files
committed
Add an explicit "How can I implement PartialOrd" doc section
Similar to the `Ord` examples but calling out that it can be defined using `cmp` from `Ord` or using `partial_cmp` in a situation that demands that.
1 parent 9efa445 commit 8b00a08

File tree

1 file changed

+44
-2
lines changed

1 file changed

+44
-2
lines changed

src/libcore/cmp.rs

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -337,15 +337,57 @@ impl PartialOrd for Ordering {
337337
/// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
338338
/// PartialOrd<V>`.
339339
///
340+
/// ## Derivable
341+
///
342+
/// This trait can be used with `#[derive]`. When `derive`d, it will produce a lexicographic
343+
/// ordering based on the top-to-bottom declaration order of the struct's members.
344+
///
345+
/// ## How can I implement `Ord`?
346+
///
340347
/// PartialOrd only requires implementation of the `partial_cmp` method, with the others generated
341348
/// from default implementations.
342349
///
343350
/// However it remains possible to implement the others separately for types which do not have a
344351
/// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
345352
/// false` (cf. IEEE 754-2008 section 5.11).
346353
///
347-
/// This trait can be used with `#[derive]`. When `derive`d, it will produce a lexicographic
348-
/// ordering based on the top-to-bottom declaration order of the struct's members.
354+
/// `PartialOrd` requires your type to be `PartialEq`.
355+
///
356+
/// If your type is `Ord`, you can implement `partial_cmp` by using `cmp`:
357+
///
358+
/// ```
359+
/// impl PartialOrd for Person {
360+
/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
361+
/// Some(self.cmp(other))
362+
/// }
363+
/// }
364+
/// ```
365+
///
366+
/// You may also find it useful to use `partial_cmp` on your type`s fields. Here
367+
/// is an example of `Person` types who have a floating-point `height` field that
368+
/// is the only field to be used for sorting:
369+
///
370+
/// ```
371+
/// use std::cmp::Ordering;
372+
///
373+
/// struct Person {
374+
/// id: u32,
375+
/// name: String,
376+
/// height: f64,
377+
/// }
378+
///
379+
/// impl PartialOrd for Person {
380+
/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
381+
/// self.height.partial_cmp(&other.height)
382+
/// }
383+
/// }
384+
///
385+
/// impl PartialEq for Person {
386+
/// fn eq(&self, other: &Self) -> bool {
387+
/// self.height == other.height
388+
/// }
389+
/// }
390+
/// ```
349391
///
350392
/// # Examples
351393
///

0 commit comments

Comments
 (0)