Skip to content

Commit 9efa445

Browse files
committed
Add an explicit "How can I implement Ord" doc section
References: - http://stackoverflow.com/q/29884402/51683 - http://stackoverflow.com/q/28387711/51683
1 parent 61bb9b2 commit 9efa445

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

src/libcore/cmp.rs

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,8 +245,48 @@ impl Ordering {
245245
/// - total and antisymmetric: exactly one of `a < b`, `a == b` or `a > b` is true; and
246246
/// - transitive, `a < b` and `b < c` implies `a < c`. The same must hold for both `==` and `>`.
247247
///
248+
/// ## Derivable
249+
///
248250
/// This trait can be used with `#[derive]`. When `derive`d, it will produce a lexicographic
249251
/// ordering based on the top-to-bottom declaration order of the struct's members.
252+
///
253+
/// ## How can I implement `Ord`?
254+
///
255+
/// `Ord` requires that the type also be `PartialOrd` and `Eq` (which requires `PartialEq`).
256+
///
257+
/// Then you must define an implementation for `cmp`. You may find it useful to use
258+
/// `cmp` on your type's fields.
259+
///
260+
/// Here's an example where you want to sort people by height only, disregarding `id`
261+
/// and `name`:
262+
///
263+
/// ```
264+
/// use std::cmp::Ordering;
265+
/// #[derive(Eq)]
266+
/// struct Person {
267+
/// id: u32,
268+
/// name: String,
269+
/// height: u32,
270+
/// }
271+
///
272+
/// impl Ord for Person {
273+
/// fn cmp(&self, other: &Self) -> Ordering {
274+
/// self.height.cmp(&other.height)
275+
/// }
276+
/// }
277+
///
278+
/// impl PartialOrd for Person {
279+
/// fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
280+
/// Some(self.cmp(other))
281+
/// }
282+
/// }
283+
///
284+
/// impl PartialEq for Person {
285+
/// fn eq(&self, other: &Self) -> bool {
286+
/// self.height == other.height
287+
/// }
288+
/// }
289+
/// ```
250290
#[stable(feature = "rust1", since = "1.0.0")]
251291
pub trait Ord: Eq + PartialOrd<Self> {
252292
/// This method returns an `Ordering` between `self` and `other`.

0 commit comments

Comments
 (0)