Trait core::cmp::PartialEq

1.0.0 · source ·
pub trait PartialEq<Rhs: ?Sized = Self> {
    // Required method
    fn eq(&self, other: &Rhs) -> bool;

    // Provided method
    fn ne(&self, other: &Rhs) -> bool { ... }
}
Expand description

Trait for equality comparisons.

x.eq(y) can also be written x == y, and x.ne(y) can be written x != y. We use the easier-to-read infix notation in the remainder of this documentation.

This trait allows for partial equality, for types that do not have a full equivalence relation. For example, in floating point numbers NaN != NaN, so floating point types implement PartialEq but not Eq. Formally speaking, when Rhs == Self, this trait corresponds to a partial equivalence relation.

Implementations must ensure that eq and ne are consistent with each other:

  • a != b if and only if !(a == b).

The default implementation of ne provides this consistency and is almost always sufficient. It should not be overridden without very good reason.

If PartialOrd or Ord are also implemented for Self and Rhs, their methods must also be consistent with PartialEq (see the documentation of those traits for the exact requirements). It’s easy to accidentally make them disagree by deriving some of the traits and manually implementing others.

The equality relation == must satisfy the following conditions (for all a, b, c of type A, B, C):

  • Symmetric: if A: PartialEq<B> and B: PartialEq<A>, then a == b implies b == a; and

  • Transitive: if A: PartialEq<B> and B: PartialEq<C> and A: PartialEq<C>, then a == b and b == c implies a == c.

Note that the B: PartialEq<A> (symmetric) and A: PartialEq<C> (transitive) impls are not forced to exist, but these requirements apply whenever they do exist.

Violating these requirements is a logic error. The behavior resulting from a logic error is not specified, but users of the trait must ensure that such logic errors do not result in undefined behavior. This means that unsafe code must not rely on the correctness of these methods.

Derivable

This trait can be used with #[derive]. When derived on structs, two instances are equal if all fields are equal, and not equal if any fields are not equal. When derived on enums, two instances are equal if they are the same variant and all fields are equal.

How can I implement PartialEq?

An example implementation for a domain in which two books are considered the same book if their ISBN matches, even if the formats differ:

enum BookFormat {
    Paperback,
    Hardback,
    Ebook,
}

struct Book {
    isbn: i32,
    format: BookFormat,
}

impl PartialEq for Book {
    fn eq(&self, other: &Self) -> bool {
        self.isbn == other.isbn
    }
}

let b1 = Book { isbn: 3, format: BookFormat::Paperback };
let b2 = Book { isbn: 3, format: BookFormat::Ebook };
let b3 = Book { isbn: 10, format: BookFormat::Paperback };

assert!(b1 == b2);
assert!(b1 != b3);
Run

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:

// The derive implements <BookFormat> == <BookFormat> comparisons
#[derive(PartialEq)]
enum BookFormat {
    Paperback,
    Hardback,
    Ebook,
}

struct Book {
    isbn: i32,
    format: BookFormat,
}

// Implement <Book> == <BookFormat> comparisons
impl PartialEq<BookFormat> for Book {
    fn eq(&self, other: &BookFormat) -> bool {
        self.format == *other
    }
}

// Implement <BookFormat> == <Book> comparisons
impl PartialEq<Book> for BookFormat {
    fn eq(&self, other: &Book) -> bool {
        *self == other.format
    }
}

let b1 = Book { isbn: 3, format: BookFormat::Paperback };

assert!(b1 == BookFormat::Paperback);
assert!(BookFormat::Ebook != b1);
Run

By changing impl PartialEq for Book to impl PartialEq<BookFormat> for Book, we allow BookFormats to be compared with Books.

A comparison like the one above, which ignores some fields of the struct, can be dangerous. It can easily lead to an unintended violation of the requirements for a partial equivalence relation. For example, if we kept the above implementation of PartialEq<Book> for BookFormat and added an implementation of PartialEq<Book> for Book (either via a #[derive] or via the manual implementation from the first example) then the result would violate transitivity:

#[derive(PartialEq)]
enum BookFormat {
    Paperback,
    Hardback,
    Ebook,
}

#[derive(PartialEq)]
struct Book {
    isbn: i32,
    format: BookFormat,
}

impl PartialEq<BookFormat> for Book {
    fn eq(&self, other: &BookFormat) -> bool {
        self.format == *other
    }
}

impl PartialEq<Book> for BookFormat {
    fn eq(&self, other: &Book) -> bool {
        *self == other.format
    }
}

fn main() {
    let b1 = Book { isbn: 1, format: BookFormat::Paperback };
    let b2 = Book { isbn: 2, format: BookFormat::Paperback };

    assert!(b1 == BookFormat::Paperback);
    assert!(BookFormat::Paperback == b2);

    // The following should hold by transitivity but doesn't.
    assert!(b1 == b2); // <-- PANICS
}
Run

Examples

let x: u32 = 0;
let y: u32 = 1;

assert_eq!(x == y, false);
assert_eq!(x.eq(&y), false);
Run

Required Methods§

source

fn eq(&self, other: &Rhs) -> bool

This method tests for self and other values to be equal, and is used by ==.

Provided Methods§

source

fn ne(&self, other: &Rhs) -> bool

This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.

Implementors§

source§

impl PartialEq<AsciiChar> for AsciiChar

1.34.0 · source§

impl PartialEq<Infallible> for Infallible

1.28.0 · source§

impl PartialEq<Alignment> for core::fmt::Alignment

1.7.0 · source§

impl PartialEq<IpAddr> for IpAddr

1.16.0 · source§

impl PartialEq<IpAddr> for Ipv4Addr

1.16.0 · source§

impl PartialEq<IpAddr> for Ipv6Addr

source§

impl PartialEq<Ipv6MulticastScope> for Ipv6MulticastScope

source§

impl PartialEq<SocketAddr> for SocketAddr

source§

impl PartialEq<FpCategory> for FpCategory

1.55.0 · source§

impl PartialEq<IntErrorKind> for IntErrorKind

source§

impl PartialEq<Which> for Which

source§

impl PartialEq<SearchStep> for SearchStep

source§

impl PartialEq<Ordering> for core::sync::atomic::Ordering

source§

impl PartialEq<Ordering> for core::cmp::Ordering

source§

impl PartialEq<bool> for bool

source§

impl PartialEq<char> for char

source§

impl PartialEq<f32> for f32

source§

impl PartialEq<f64> for f64

source§

impl PartialEq<i8> for i8

source§

impl PartialEq<i16> for i16

source§

impl PartialEq<i32> for i32

source§

impl PartialEq<i64> for i64

source§

impl PartialEq<i128> for i128

source§

impl PartialEq<isize> for isize

source§

impl PartialEq<!> for !

source§

impl PartialEq<str> for str

source§

impl PartialEq<u8> for u8

source§

impl PartialEq<u16> for u16

source§

impl PartialEq<u32> for u32

source§

impl PartialEq<u64> for u64

source§

impl PartialEq<u128> for u128

source§

impl PartialEq<()> for ()

source§

impl PartialEq<usize> for usize

source§

impl PartialEq<AllocError> for AllocError

1.28.0 · source§

impl PartialEq<Layout> for Layout

1.50.0 · source§

impl PartialEq<LayoutError> for LayoutError

source§

impl PartialEq<TypeId> for TypeId

1.27.0 · source§

impl PartialEq<CpuidResult> for CpuidResult

Available on x86 or x86-64 only.
1.34.0 · source§

impl PartialEq<CharTryFromError> for CharTryFromError

1.9.0 · source§

impl PartialEq<DecodeUtf16Error> for DecodeUtf16Error

1.20.0 · source§

impl PartialEq<ParseCharError> for ParseCharError

1.59.0 · source§

impl PartialEq<TryFromCharError> for TryFromCharError

source§

impl PartialEq<CStr> for CStr

1.69.0 · source§

impl PartialEq<FromBytesUntilNulError> for FromBytesUntilNulError

1.64.0 · source§

impl PartialEq<FromBytesWithNulError> for FromBytesWithNulError

source§

impl PartialEq<Error> for Error

1.33.0 · source§

impl PartialEq<PhantomPinned> for PhantomPinned

source§

impl PartialEq<Assume> for Assume

source§

impl PartialEq<AddrParseError> for AddrParseError

1.16.0 · source§

impl PartialEq<Ipv4Addr> for IpAddr

source§

impl PartialEq<Ipv4Addr> for Ipv4Addr

1.16.0 · source§

impl PartialEq<Ipv6Addr> for IpAddr

source§

impl PartialEq<Ipv6Addr> for Ipv6Addr

source§

impl PartialEq<SocketAddrV4> for SocketAddrV4

source§

impl PartialEq<SocketAddrV6> for SocketAddrV6

1.34.0 · source§

impl PartialEq<NonZeroI8> for NonZeroI8

1.34.0 · source§

impl PartialEq<NonZeroI16> for NonZeroI16

1.34.0 · source§

impl PartialEq<NonZeroI32> for NonZeroI32

1.34.0 · source§

impl PartialEq<NonZeroI64> for NonZeroI64

1.34.0 · source§

impl PartialEq<NonZeroI128> for NonZeroI128

1.34.0 · source§

impl PartialEq<NonZeroIsize> for NonZeroIsize

1.28.0 · source§

impl PartialEq<NonZeroU8> for NonZeroU8

1.28.0 · source§

impl PartialEq<NonZeroU16> for NonZeroU16

1.28.0 · source§

impl PartialEq<NonZeroU32> for NonZeroU32

1.28.0 · source§

impl PartialEq<NonZeroU64> for NonZeroU64

1.28.0 · source§

impl PartialEq<NonZeroU128> for NonZeroU128

1.28.0 · source§

impl PartialEq<NonZeroUsize> for NonZeroUsize

source§

impl PartialEq<ParseIntError> for ParseIntError

1.34.0 · source§

impl PartialEq<TryFromIntError> for TryFromIntError

source§

impl PartialEq<RangeFull> for RangeFull

source§

impl PartialEq<Alignment> for core::ptr::Alignment

source§

impl PartialEq<ParseBoolError> for ParseBoolError

source§

impl PartialEq<Utf8Error> for Utf8Error

1.36.0 · source§

impl PartialEq<RawWaker> for RawWaker

1.36.0 · source§

impl PartialEq<RawWakerVTable> for RawWakerVTable

1.3.0 · source§

impl PartialEq<Duration> for Duration

1.66.0 · source§

impl PartialEq<TryFromFloatSecsError> for TryFromFloatSecsError

1.10.0 · source§

impl<'a> PartialEq<Location<'a>> for Location<'a>

source§

impl<'a> PartialEq<Utf8Chunk<'a>> for Utf8Chunk<'a>

source§

impl<A, B> PartialEq<[B]> for [A]where A: PartialEq<B>,

source§

impl<A, B, const N: usize> PartialEq<&[B]> for [A; N]where A: PartialEq<B>,

source§

impl<A, B, const N: usize> PartialEq<&mut [B]> for [A; N]where A: PartialEq<B>,

source§

impl<A, B, const N: usize> PartialEq<[A; N]> for &[B]where B: PartialEq<A>,

source§

impl<A, B, const N: usize> PartialEq<[A; N]> for &mut [B]where B: PartialEq<A>,

source§

impl<A, B, const N: usize> PartialEq<[A; N]> for [B]where B: PartialEq<A>,

source§

impl<A, B, const N: usize> PartialEq<[B; N]> for [A; N]where A: PartialEq<B>,

source§

impl<A, B, const N: usize> PartialEq<[B]> for [A; N]where A: PartialEq<B>,

source§

impl<A, B: ?Sized> PartialEq<&B> for &Awhere A: PartialEq<B> + ?Sized,

source§

impl<A, B: ?Sized> PartialEq<&B> for &mut Awhere A: PartialEq<B> + ?Sized,

source§

impl<A, B: ?Sized> PartialEq<&mut B> for &Awhere A: PartialEq<B> + ?Sized,

source§

impl<A, B: ?Sized> PartialEq<&mut B> for &mut Awhere A: PartialEq<B> + ?Sized,

1.55.0 · source§

impl<B: PartialEq, C: PartialEq> PartialEq<ControlFlow<B, C>> for ControlFlow<B, C>

source§

impl<Dyn: ?Sized> PartialEq<DynMetadata<Dyn>> for DynMetadata<Dyn>

1.4.0 · source§

impl<F: FnPtr> PartialEq<F> for F

1.29.0 · source§

impl<H> PartialEq<BuildHasherDefault<H>> for BuildHasherDefault<H>

source§

impl<Idx: PartialEq> PartialEq<Range<Idx>> for Range<Idx>

source§

impl<Idx: PartialEq> PartialEq<RangeFrom<Idx>> for RangeFrom<Idx>

1.26.0 · source§

impl<Idx: PartialEq> PartialEq<RangeInclusive<Idx>> for RangeInclusive<Idx>

source§

impl<Idx: PartialEq> PartialEq<RangeTo<Idx>> for RangeTo<Idx>

1.26.0 · source§

impl<Idx: PartialEq> PartialEq<RangeToInclusive<Idx>> for RangeToInclusive<Idx>

1.41.0 · source§

impl<P: Deref, Q: Deref> PartialEq<Pin<Q>> for Pin<P>where P::Target: PartialEq<Q::Target>,

source§

impl<T> PartialEq<(T,)> for (T₁, T₂, …, Tₙ)where T: ?Sized + PartialEq,

This trait is implemented for tuples up to twelve items long.

1.21.0 · source§

impl<T> PartialEq<Discriminant<T>> for Discriminant<T>

source§

impl<T, const LANES: usize> PartialEq<Mask<T, LANES>> for Mask<T, LANES>where T: MaskElement + PartialEq, LaneCount<LANES>: SupportedLaneCount,

source§

impl<T, const N: usize> PartialEq<Simd<T, N>> for Simd<T, N>where LaneCount<N>: SupportedLaneCount, T: SimdElement + PartialEq,

source§

impl<T: PartialEq + Copy> PartialEq<Cell<T>> for Cell<T>

1.20.0 · source§

impl<T: PartialEq + ?Sized> PartialEq<ManuallyDrop<T>> for ManuallyDrop<T>

1.17.0 · source§

impl<T: PartialEq> PartialEq<Bound<T>> for Bound<T>

source§

impl<T: PartialEq> PartialEq<Option<T>> for Option<T>

1.36.0 · source§

impl<T: PartialEq> PartialEq<Poll<T>> for Poll<T>

1.70.0 · source§

impl<T: PartialEq> PartialEq<OnceCell<T>> for OnceCell<T>

1.74.0 · source§

impl<T: PartialEq> PartialEq<Saturating<T>> for Saturating<T>

source§

impl<T: PartialEq> PartialEq<Wrapping<T>> for Wrapping<T>

1.19.0 · source§

impl<T: PartialEq> PartialEq<Reverse<T>> for Reverse<T>

source§

impl<T: PartialEq, E: PartialEq> PartialEq<Result<T, E>> for Result<T, E>

source§

impl<T: ?Sized + PartialEq> PartialEq<RefCell<T>> for RefCell<T>

source§

impl<T: ?Sized> PartialEq<*const T> for *const T

source§

impl<T: ?Sized> PartialEq<*mut T> for *mut T

source§

impl<T: ?Sized> PartialEq<PhantomData<T>> for PhantomData<T>

1.25.0 · source§

impl<T: ?Sized> PartialEq<NonNull<T>> for NonNull<T>

source§

impl<Y: PartialEq, R: PartialEq> PartialEq<GeneratorState<Y, R>> for GeneratorState<Y, R>

This documentation is an old archive. Please see https://rust.docs.kernel.org instead.