Trait PartialEq
trait PartialEq<Rhs: PointeeSized = Self>: PointeeSized
Trait for comparisons using the equality operator.
Implementing this trait for types provides the == and != operators for
those types.
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 comparisons using the equality operator, 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
[trait@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 != bif 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):
-
Symmetry: if
A: PartialEq<B>andB: PartialEq<A>, thena == bimpliesb == a; and -
Transitivity: if
A: PartialEq<B>andB: PartialEq<C>andA: PartialEq<C>, thena == bandb == cimpliesa == c. This must also work for longer chains, such as whenA: PartialEq<B>,B: PartialEq<C>,C: PartialEq<D>, andA: PartialEq<D>all exist.
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.
Cross-crate considerations
Upholding the requirements stated above can become tricky when one crate implements PartialEq
for a type of another crate (i.e., to allow comparing one of its own types with a type from the
standard library). The recommendation is to never implement this trait for a foreign type. In
other words, such a crate should do impl PartialEq<ForeignType> for LocalType, but it should
not do impl PartialEq<LocalType> for ForeignType.
This avoids the problem of transitive chains that criss-cross crate boundaries: for all local
types T, you may assume that no other crate will add impls that allow comparing T == U. In
other words, if other crates add impls that allow building longer transitive chains U1 == ... == T == V1 == ..., then all the types that appear to the right of T must be types that the
crate defining T already knows about. This rules out transitive chains where downstream crates
can add new impls that "stitch together" comparisons of foreign types in ways that violate
transitivity.
Not having such foreign impls also avoids forward compatibility issues where one crate adding
more PartialEq implementations can cause build failures in downstream crates.
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:
let b1 = Book ;
let b2 = Book ;
let b3 = Book ;
assert!;
assert!;
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
// Implement <Book> == <BookFormat> comparisons
// Implement <BookFormat> == <Book> comparisons
let b1 = Book ;
assert!;
assert!;
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
}
Examples
let x: u32 = 0;
let y: u32 = 1;
assert_eq!;
assert_eq!;
Required Methods
fn eq(self: &Self, other: &Rhs) -> boolTests for
selfandothervalues to be equal, and is used by==.
Provided Methods
fn ne(self: &Self, other: &Rhs) -> boolTests for
!=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Implementors
impl<T: $crate::cmp::PartialEq> PartialEq for Poll<T>impl<'a> PartialEq for PhantomCovariantLifetime<'a>impl PartialEq for CStrimpl PartialEq for charimpl PartialEq for DebugAsHeximpl<A, B: PointeeSized> PartialEq for &Aimpl<T, U, N: usize> PartialEq for [T; N]impl PartialEq for CharTryFromErrorimpl<F: FnPtr> PartialEq for Fimpl<T: ~const PartialEq> PartialEq for (T)impl<F> PartialEq for fn(_: T) -> Retimpl PartialEq for i16impl PartialEq for PhantomPinnedimpl<'a> PartialEq for &[u8]impl PartialEq for Ipv6Addrimpl PartialEq for strimpl<T> PartialEq for Discriminant<T>impl<T: ~const $crate::cmp::PartialEq, E: ~const $crate::cmp::PartialEq> PartialEq for Result<T, E>impl<Idx: ~const $crate::cmp::PartialEq> PartialEq for RangeInclusive<Idx>impl<N: usize> PartialEq for crate::bstr::ByteStrimpl PartialEq for Location<'_>impl PartialEq for u64impl<'a> PartialEq for PhantomContravariantLifetime<'a>impl<T, U, N: usize> PartialEq for &mut [T]impl PartialEq for IpAddrimpl PartialEq for FormattingOptionsimpl PartialEq for DecodeUtf16Errorimpl PartialEq for Alignmentimpl PartialEq for Orderingimpl<Dyn: PointeeSized> PartialEq for DynMetadata<Dyn>impl PartialEq for f32impl PartialEq for CpuidResultimpl PartialEq for RawWakerimpl<B: ~const $crate::cmp::PartialEq, C: ~const $crate::cmp::PartialEq> PartialEq for ControlFlow<B, C>impl<'a> PartialEq for crate::bstr::ByteStrimpl PartialEq for IpAddrimpl<'a> PartialEq for Utf8Pattern<'a>impl PartialEq for usizeimpl<A, B: PointeeSized> PartialEq for &mut Aimpl PartialEq for SimdAlignimpl<T: ?Sized + PartialEq> PartialEq for ManuallyDrop<T>impl<T, U, N: usize> PartialEq for [T]impl PartialEq for Orderingimpl<Idx: $crate::cmp::PartialEq> PartialEq for RangeToInclusive<Idx>impl PartialEq for ParseIntErrorimpl<N: usize> PartialEq for &[u8; N]impl PartialEq for i32impl<'a> PartialEq for PhantomInvariantLifetime<'a>impl PartialEq for AsciiCharimpl PartialEq for Ipv4Addrimpl<H> PartialEq for BuildHasherDefault<H>impl PartialEq for TryFromCharErrorimpl<T: ~const $crate::cmp::PartialEq> PartialEq for Reverse<T>impl<T, N: usize> PartialEq for Mask<T, N>impl<Ptr: Deref, Q: Deref> PartialEq for Pin<Ptr>impl PartialEq for RawWakerVTableimpl<Y: $crate::cmp::PartialEq, R: $crate::cmp::PartialEq> PartialEq for CoroutineState<Y, R>impl<'a> PartialEq for strimpl PartialEq for AddrParseErrorimpl PartialEq for u128impl PartialEq for SearchStepimpl PartialEq for TryFromIntErrorimpl<T, U> PartialEq for Exclusive<T>impl PartialEq for f64impl<T: ~const $crate::cmp::PartialEq> PartialEq for Bound<T>impl<T: PartialEq> PartialEq for OnceCell<T>impl<T> PartialEq for PhantomCovariant<T>impl PartialEq for crate::bstr::ByteStrimpl PartialEq for AtomicOrderingimpl PartialEq for Ipv6Addrimpl PartialEq for u8impl<T, U> PartialEq for [T]impl<A, B: PointeeSized> PartialEq for &Aimpl<T, U, N: usize> PartialEq for [T; N]impl PartialEq for CStrimpl<T> PartialEq for NonZero<T>impl<Idx: ~const $crate::cmp::PartialEq> PartialEq for Range<Idx>impl PartialEq for i64impl PartialEq for Layoutimpl PartialEq for RangeFullimpl<'a> PartialEq for crate::bstr::ByteStrimpl PartialEq for SocketAddrimpl<'a> PartialEq for Utf8Chunk<'a>impl PartialEq for IntErrorKindimpl PartialEq for ()impl PartialEq for Alignmentimpl<T, N: usize> PartialEq for Simd<T, N>impl<T: $crate::cmp::PartialEq> PartialEq for Saturating<T>impl PartialEq for TypeIdimpl<T: PartialEq + Copy> PartialEq for Cell<T>impl PartialEq for isizeimpl<T> PartialEq for PhantomContravariant<T>impl<'a> PartialEq for crate::bstr::ByteStrimpl PartialEq for Ipv6MulticastScopeimpl PartialEq for GetDisjointMutErrorimpl PartialEq for FromBytesWithNulErrorimpl PartialEq for f128impl<Idx: $crate::cmp::PartialEq> PartialEq for RangeInclusive<Idx>impl PartialEq for FpCategoryimpl PartialEq for LayoutErrorimpl<Idx: ~const $crate::cmp::PartialEq> PartialEq for Range<Idx>impl<'a> PartialEq for &strimpl PartialEq for SocketAddrV4impl PartialEq for Durationimpl PartialEq for u16impl<A, B: PointeeSized> PartialEq for &mut Aimpl<T, U, N: usize> PartialEq for &[T]impl PartialEq for Assumeimpl PartialEq for Errorimpl<T: ?Sized + PartialEq> PartialEq for RefCell<T>impl<T: PointeeSized> PartialEq for *const Timpl PartialEq for i128impl<T> PartialEq for PhantomInvariant<T>impl<'a> PartialEq for [u8]impl PartialEq for IpAddrimpl PartialEq for Utf8Errorimpl PartialEq for FromBytesUntilNulErrorimpl PartialEq for boolimpl PartialEq for neverimpl<T, U, N: usize> PartialEq for [T; N]impl<Idx: ~const $crate::cmp::PartialEq> PartialEq for RangeFrom<Idx>impl PartialEq for AllocErrorimpl<Idx: ~const $crate::cmp::PartialEq> PartialEq for RangeFrom<Idx>impl<N: usize> PartialEq for crate::bstr::ByteStrimpl PartialEq for SocketAddrV6impl PartialEq for i8impl PartialEq for TryFromFloatSecsErrorimpl<T: $crate::cmp::PartialEq> PartialEq for Wrapping<T>impl PartialEq for Infallibleimpl PartialEq for Signimpl PartialEq for ParseCharErrorimpl<T: PointeeSized> PartialEq for *mut Timpl PartialEq for Localityimpl<T: PointeeSized> PartialEq for PhantomData<T>impl<'a> PartialEq for crate::bstr::ByteStrimpl PartialEq for Ipv4Addrimpl PartialEq for u32impl PartialEq for ParseBoolErrorimpl<T, U, N: usize> PartialEq for [T; N]impl<T: PointeeSized> PartialEq for NonNull<T>impl<Idx: $crate::cmp::PartialEq> PartialEq for RangeToInclusive<Idx>impl PartialEq for f16impl<Idx: ~const $crate::cmp::PartialEq> PartialEq for RangeTo<Idx>impl<N: usize> PartialEq for [u8; N]impl<T: ~const PartialEq> PartialEq for Option<T>