about summary refs log tree commit diff
path: root/src/libcore
diff options
context:
space:
mode:
authorCarol (Nichols || Goulding) <carol.nichols@gmail.com>2016-05-22 19:14:38 -0400
committerCarol (Nichols || Goulding) <carol.nichols@gmail.com>2016-05-23 10:03:44 -0400
commit8b00a086e78faa7ca0e0be539f0587df41b31fb7 (patch)
tree65b65fc17ff457f4a8dea44b454dfc71e023c82f /src/libcore
parent9efa44565610054a790c64cda8cdb086e5fbc21c (diff)
downloadrust-8b00a086e78faa7ca0e0be539f0587df41b31fb7.tar.gz
rust-8b00a086e78faa7ca0e0be539f0587df41b31fb7.zip
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.
Diffstat (limited to 'src/libcore')
-rw-r--r--src/libcore/cmp.rs46
1 files changed, 44 insertions, 2 deletions
diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs
index 15e128c57da..5b8620f4b8e 100644
--- a/src/libcore/cmp.rs
+++ b/src/libcore/cmp.rs
@@ -337,6 +337,13 @@ impl PartialOrd for Ordering {
 /// transitively: if `T: PartialOrd<U>` and `U: PartialOrd<V>` then `U: PartialOrd<T>` and `T:
 /// PartialOrd<V>`.
 ///
+/// ## Derivable
+///
+/// This trait can be used with `#[derive]`. When `derive`d, it will produce a lexicographic
+/// ordering based on the top-to-bottom declaration order of the struct's members.
+///
+/// ## How can I implement `Ord`?
+///
 /// PartialOrd only requires implementation of the `partial_cmp` method, with the others generated
 /// from default implementations.
 ///
@@ -344,8 +351,43 @@ impl PartialOrd for Ordering {
 /// total order. For example, for floating point numbers, `NaN < 0 == false` and `NaN >= 0 ==
 /// false` (cf. IEEE 754-2008 section 5.11).
 ///
-/// This trait can be used with `#[derive]`. When `derive`d, it will produce a lexicographic
-/// ordering based on the top-to-bottom declaration order of the struct's members.
+/// `PartialOrd` requires your type to be `PartialEq`.
+///
+/// If your type is `Ord`, you can implement `partial_cmp` by using `cmp`:
+///
+/// ```
+/// impl PartialOrd for Person {
+///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+///         Some(self.cmp(other))
+///     }
+/// }
+/// ```
+///
+/// You may also find it useful to use `partial_cmp` on your type`s fields. Here
+/// is an example of `Person` types who have a floating-point `height` field that
+/// is the only field to be used for sorting:
+///
+/// ```
+/// use std::cmp::Ordering;
+///
+/// struct Person {
+///     id: u32,
+///     name: String,
+///     height: f64,
+/// }
+///
+/// impl PartialOrd for Person {
+///     fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
+///         self.height.partial_cmp(&other.height)
+///     }
+/// }
+///
+/// impl PartialEq for Person {
+///     fn eq(&self, other: &Self) -> bool {
+///         self.height == other.height
+///     }
+/// }
+/// ```
 ///
 /// # Examples
 ///