From 3995bff26ce657ec6bac43cb0bdb4769e36ccc67 Mon Sep 17 00:00:00 2001 From: Guillaume Gomez Date: Tue, 21 Aug 2018 23:24:23 +0200 Subject: [PATCH] Add another PartialEq example --- src/libcore/cmp.rs | 85 +++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 84 insertions(+), 1 deletion(-) diff --git a/src/libcore/cmp.rs b/src/libcore/cmp.rs index 58d6c4f5e0923..ef7d83a0993da 100644 --- a/src/libcore/cmp.rs +++ b/src/libcore/cmp.rs @@ -75,7 +75,12 @@ use self::Ordering::*; /// the same book if their ISBN matches, even if the formats differ: /// /// ``` -/// enum BookFormat { Paperback, Hardback, Ebook } +/// enum BookFormat { +/// Paperback, +/// Hardback, +/// Ebook, +/// } +/// /// struct Book { /// isbn: i32, /// format: BookFormat, @@ -95,6 +100,84 @@ use self::Ordering::*; /// assert!(b1 != b3); /// ``` /// +/// ## How can I compare two different types? +/// +/// The type you can compare with is controlled by `PartialEq`'s type parameter. +/// For example, let's tweak our previous code a bit: +/// +/// ``` +/// enum BookFormat { +/// Paperback, +/// Hardback, +/// Ebook, +/// } +/// +/// struct Book { +/// isbn: i32, +/// format: BookFormat, +/// } +/// +/// impl PartialEq for Book { +/// fn eq(&self, other: &BookFormat) -> bool { +/// match (&self.format, other) { +/// (BookFormat::Paperback, BookFormat::Paperback) => true, +/// (BookFormat::Hardback, BookFormat::Hardback) => true, +/// (BookFormat::Ebook, BookFormat::Ebook) => true, +/// (_, _) => false, +/// } +/// } +/// } +/// +/// let b1 = Book { isbn: 3, format: BookFormat::Paperback }; +/// +/// assert!(b1 == BookFormat::Paperback); +/// assert!(b1 != BookFormat::Ebook); +/// ``` +/// +/// By changing `impl PartialEq for Book` to `impl PartialEq for Book`, +/// we've changed what type we can use on the right side of the `==` operator. +/// This lets us use it in the `assert!` statements at the bottom. +/// +/// You can also combine these implementations to let the `==` operator work with +/// two different types: +/// +/// ``` +/// enum BookFormat { +/// Paperback, +/// Hardback, +/// Ebook, +/// } +/// +/// struct Book { +/// isbn: i32, +/// format: BookFormat, +/// } +/// +/// impl PartialEq for Book { +/// fn eq(&self, other: &BookFormat) -> bool { +/// match (&self.format, other) { +/// (&BookFormat::Paperback, &BookFormat::Paperback) => true, +/// (&BookFormat::Hardback, &BookFormat::Hardback) => true, +/// (&BookFormat::Ebook, &BookFormat::Ebook) => true, +/// (_, _) => false, +/// } +/// } +/// } +/// +/// impl PartialEq for Book { +/// fn eq(&self, other: &Book) -> bool { +/// self.isbn == other.isbn +/// } +/// } +/// +/// let b1 = Book { isbn: 3, format: BookFormat::Paperback }; +/// let b2 = Book { isbn: 3, format: BookFormat::Ebook }; +/// +/// assert!(b1 == BookFormat::Paperback); +/// assert!(b1 != BookFormat::Ebook); +/// assert!(b1 == b2); +/// ``` +/// /// # Examples /// /// ```