Skip to content

Commit e831c72

Browse files
committed
Add an explicit "How can I implement PartialEq"? doc section
Including an example of a custom implementation. I put this expanded section after the `Derivable` section to encourage use of that first.
1 parent fc467b3 commit e831c72

File tree

1 file changed

+31
-4
lines changed

1 file changed

+31
-4
lines changed

src/libcore/cmp.rs

Lines changed: 31 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -53,16 +53,43 @@ use option::Option::{self, Some};
5353
/// symmetrically and transitively: if `T: PartialEq<U>` and `U: PartialEq<V>`
5454
/// then `U: PartialEq<T>` and `T: PartialEq<V>`.
5555
///
56-
/// PartialEq only requires the `eq` method to be implemented; `ne` is defined
57-
/// in terms of it by default. Any manual implementation of `ne` *must* respect
58-
/// the rule that `eq` is a strict inverse of `ne`; that is, `!(a == b)` if and
59-
/// only if `a != b`.
56+
/// ## Derivable
6057
///
6158
/// This trait can be used with `#[derive]`. When `derive`d on structs, two
6259
/// instances are equal if all fields are equal, and non equal if any fields
6360
/// are not equal. When `derive`d on enums, each variant is equal to itself
6461
/// and not equal to the other variants.
6562
///
63+
/// ## How can I implement `PartialEq`?
64+
///
65+
/// PartialEq only requires the `eq` method to be implemented; `ne` is defined
66+
/// in terms of it by default. Any manual implementation of `ne` *must* respect
67+
/// the rule that `eq` is a strict inverse of `ne`; that is, `!(a == b)` if and
68+
/// only if `a != b`.
69+
///
70+
/// An example implementation for a domain in which two books are considered
71+
/// the same book if their ISBN matches, even if the formats differ:
72+
///
73+
/// ```
74+
/// enum BookFormat { Paperback, Hardback, Ebook }
75+
/// struct Book {
76+
/// isbn: i32,
77+
/// format: BookFormat,
78+
/// }
79+
/// impl PartialEq for Book {
80+
/// fn eq(&self, other: &Self) -> bool {
81+
/// self.isbn == other.isbn
82+
/// }
83+
/// }
84+
///
85+
/// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
86+
/// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
87+
/// let b3 = Book { isbn: 10, format: BookFormat::Paperback };
88+
///
89+
/// assert!(b1 == b2);
90+
/// assert!(b1 != b3);
91+
/// ```
92+
///
6693
/// # Examples
6794
///
6895
/// ```

0 commit comments

Comments
 (0)