@@ -135,17 +135,23 @@ use self::Ordering::*;
135
135
/// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
136
136
/// we allow `BookFormat`s to be compared with `Book`s.
137
137
///
138
- /// You can also combine these implementations to let the `==` operator work with
139
- /// two different types:
140
- ///
141
- /// ```
138
+ /// A comparison like the one above, which ignores some fields of the struct,
139
+ /// can be dangerous. It can easily lead to an unintended violation of the
140
+ /// requirements for a partial equivalence relation. For example, if we kept
141
+ /// the above implementation of `PartialEq<Book>` for `BookFormat` and added an
142
+ /// implementation of `PartialEq<Book>` for `Book` (either via a `#[derive]` or
143
+ /// via the manual implementation from the first example) then the result would
144
+ /// violate transitivity:
145
+ ///
146
+ /// ```should_panic
142
147
/// #[derive(PartialEq)]
143
148
/// enum BookFormat {
144
149
/// Paperback,
145
150
/// Hardback,
146
151
/// Ebook,
147
152
/// }
148
153
///
154
+ /// #[derive(PartialEq)]
149
155
/// struct Book {
150
156
/// isbn: i32,
151
157
/// format: BookFormat,
@@ -163,18 +169,16 @@ use self::Ordering::*;
163
169
/// }
164
170
/// }
165
171
///
166
- /// impl PartialEq for Book {
167
- /// fn eq(&self, other: &Book) -> bool {
168
- /// self.isbn == other.isbn
169
- /// }
170
- /// }
172
+ /// fn main() {
173
+ /// let b1 = Book { isbn: 1, format: BookFormat::Paperback };
174
+ /// let b2 = Book { isbn: 2, format: BookFormat::Paperback };
171
175
///
172
- /// let b1 = Book { isbn: 3, format: BookFormat::Paperback } ;
173
- /// let b2 = Book { isbn: 3, format: BookFormat::Ebook } ;
176
+ /// assert!(b1 == BookFormat::Paperback) ;
177
+ /// assert!( BookFormat::Paperback == b2) ;
174
178
///
175
- /// assert!(b1 == BookFormat::Paperback);
176
- /// assert!(BookFormat::Ebook != b1);
177
- /// assert!(b1 == b2);
179
+ /// // The following should hold by transitivity but doesn't.
180
+ /// assert!(b1 == b2); // <-- PANICS
181
+ /// }
178
182
/// ```
179
183
///
180
184
/// # Examples
0 commit comments