@@ -75,7 +75,12 @@ use self::Ordering::*;
7575/// the same book if their ISBN matches, even if the formats differ:
7676///
7777/// ```
78- /// enum BookFormat { Paperback, Hardback, Ebook }
78+ /// enum BookFormat {
79+ /// Paperback,
80+ /// Hardback,
81+ /// Ebook,
82+ /// }
83+ ///
7984/// struct Book {
8085/// isbn: i32,
8186/// format: BookFormat,
@@ -95,6 +100,84 @@ use self::Ordering::*;
95100/// assert!(b1 != b3);
96101/// ```
97102///
103+ /// ## How can I compare two different types?
104+ ///
105+ /// The type you can compare with is controlled by `PartialEq`'s type parameter.
106+ /// For example, let's tweak our previous code a bit:
107+ ///
108+ /// ```
109+ /// enum BookFormat {
110+ /// Paperback,
111+ /// Hardback,
112+ /// Ebook,
113+ /// }
114+ ///
115+ /// struct Book {
116+ /// isbn: i32,
117+ /// format: BookFormat,
118+ /// }
119+ ///
120+ /// impl PartialEq<BookFormat> for Book {
121+ /// fn eq(&self, other: &BookFormat) -> bool {
122+ /// match (&self.format, other) {
123+ /// (BookFormat::Paperback, BookFormat::Paperback) => true,
124+ /// (BookFormat::Hardback, BookFormat::Hardback) => true,
125+ /// (BookFormat::Ebook, BookFormat::Ebook) => true,
126+ /// (_, _) => false,
127+ /// }
128+ /// }
129+ /// }
130+ ///
131+ /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
132+ ///
133+ /// assert!(b1 == BookFormat::Paperback);
134+ /// assert!(b1 != BookFormat::Ebook);
135+ /// ```
136+ ///
137+ /// By changing `impl PartialEq for Book` to `impl PartialEq<BookFormat> for Book`,
138+ /// we've changed what type we can use on the right side of the `==` operator.
139+ /// This lets us use it in the `assert!` statements at the bottom.
140+ ///
141+ /// You can also combine these implementations to let the `==` operator work with
142+ /// two different types:
143+ ///
144+ /// ```
145+ /// enum BookFormat {
146+ /// Paperback,
147+ /// Hardback,
148+ /// Ebook,
149+ /// }
150+ ///
151+ /// struct Book {
152+ /// isbn: i32,
153+ /// format: BookFormat,
154+ /// }
155+ ///
156+ /// impl PartialEq<BookFormat> for Book {
157+ /// fn eq(&self, other: &BookFormat) -> bool {
158+ /// match (&self.format, other) {
159+ /// (&BookFormat::Paperback, &BookFormat::Paperback) => true,
160+ /// (&BookFormat::Hardback, &BookFormat::Hardback) => true,
161+ /// (&BookFormat::Ebook, &BookFormat::Ebook) => true,
162+ /// (_, _) => false,
163+ /// }
164+ /// }
165+ /// }
166+ ///
167+ /// impl PartialEq for Book {
168+ /// fn eq(&self, other: &Book) -> bool {
169+ /// self.isbn == other.isbn
170+ /// }
171+ /// }
172+ ///
173+ /// let b1 = Book { isbn: 3, format: BookFormat::Paperback };
174+ /// let b2 = Book { isbn: 3, format: BookFormat::Ebook };
175+ ///
176+ /// assert!(b1 == BookFormat::Paperback);
177+ /// assert!(b1 != BookFormat::Ebook);
178+ /// assert!(b1 == b2);
179+ /// ```
180+ ///
98181/// # Examples
99182///
100183/// ```
0 commit comments