Skip to content

Commit 1445a06

Browse files
authored
bring back the example i removed, also add symmetry and simplify impl
1 parent 423a5bb commit 1445a06

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

src/libcore/cmp.rs

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,48 @@ use self::Ordering::*;
132132
/// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
133133
/// we allow `BookFormat`s to be compared with `Book`s.
134134
///
135+
/// You can also combine these implementations to let the `==` operator work with
136+
/// two different types:
137+
///
138+
/// ```
139+
/// #[derive(PartialEq)]
140+
/// enum BookFormat {
141+
/// Paperback,
142+
/// Hardback,
143+
/// Ebook,
144+
/// }
145+
///
146+
/// struct Book {
147+
/// isbn: i32,
148+
/// format: BookFormat,
149+
/// }
150+
///
151+
/// impl PartialEq<BookFormat> for Book {
152+
/// fn eq(&self, other: &BookFormat) -> bool {
153+
/// self.format == *other
154+
/// }
155+
/// }
156+
///
157+
/// impl PartialEq<Book> for BookFormat {
158+
/// fn eq(&self, other: &Book) -> bool {
159+
/// *self == other.format
160+
/// }
161+
/// }
162+
///
163+
/// impl PartialEq for Book {
164+
/// fn eq(&self, other: &Book) -> bool {
165+
/// self.isbn == other.isbn
166+
/// }
167+
/// }
168+
///
169+
/// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
170+
/// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
171+
///
172+
/// assert!(b1 == BookFormat::Paperback);
173+
/// assert!(b1 != BookFormat::Ebook);
174+
/// assert!(b1 == b2);
175+
/// ```
176+
///
135177
/// # Examples
136178
///
137179
/// ```

0 commit comments

Comments
 (0)