@@ -107,67 +107,29 @@ use self::Ordering::*;
107
107
/// format: BookFormat,
108
108
/// }
109
109
///
110
+ /// // Implement <Book> == <BookFormat> comparisons
110
111
/// impl PartialEq<BookFormat> for Book {
111
112
/// fn eq(&self, other: &BookFormat) -> bool {
112
- /// match (&self.format, other) {
113
- /// (BookFormat::Paperback, BookFormat::Paperback) => true,
114
- /// (BookFormat::Hardback, BookFormat::Hardback) => true,
115
- /// (BookFormat::Ebook, BookFormat::Ebook) => true,
116
- /// (_, _) => false,
117
- /// }
113
+ /// self.format == *other
118
114
/// }
119
115
/// }
120
116
///
121
- /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
122
- ///
123
- /// assert!(b1 == BookFormat::Paperback);
124
- /// assert!(b1 != BookFormat::Ebook);
125
- /// ```
126
- ///
127
- /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
128
- /// we've changed what type we can use on the right side of the `==` operator.
129
- /// This lets us use it in the `assert!` statements at the bottom.
130
- ///
131
- /// You can also combine these implementations to let the `==` operator work with
132
- /// two different types:
133
- ///
134
- /// ```
135
- /// enum BookFormat {
136
- /// Paperback,
137
- /// Hardback,
138
- /// Ebook,
139
- /// }
140
- ///
141
- /// struct Book {
142
- /// isbn: i32,
143
- /// format: BookFormat,
144
- /// }
145
- ///
146
- /// impl PartialEq<BookFormat> for Book {
147
- /// fn eq(&self, other: &BookFormat) -> bool {
148
- /// match (&self.format, other) {
149
- /// (&BookFormat::Paperback, &BookFormat::Paperback) => true,
150
- /// (&BookFormat::Hardback, &BookFormat::Hardback) => true,
151
- /// (&BookFormat::Ebook, &BookFormat::Ebook) => true,
152
- /// (_, _) => false,
153
- /// }
154
- /// }
155
- /// }
156
- ///
157
- /// impl PartialEq for Book {
117
+ /// // Implement <BookFormat> == <Book> comparisons
118
+ /// impl PartialEq<Book> for BookFormat {
158
119
/// fn eq(&self, other: &Book) -> bool {
159
- /// self.isbn == other.isbn
120
+ /// *other == self.format
160
121
/// }
161
122
/// }
162
123
///
163
124
/// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
164
- /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
165
125
///
166
126
/// assert!(b1 == BookFormat::Paperback);
167
- /// assert!(b1 != BookFormat::Ebook);
168
- /// assert!(b1 == b2);
127
+ /// assert!(BookFormat::Ebook != b1);
169
128
/// ```
170
129
///
130
+ /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
131
+ /// we allow `BookFormat`s to be compared with `Book`s.
132
+ ///
171
133
/// # Examples
172
134
///
173
135
/// ```
0 commit comments