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 PartialEq for f16impl<T, U, N: usize> PartialEq for [T; N]impl PartialEq for RawWakerVTableimpl PartialEq for f64impl<T, U, N: usize> PartialEq for [T; N]impl PartialEq for AllocErrorimpl<Idx: $crate::cmp::PartialEq> PartialEq for RangeInclusive<Idx>impl<T: ~const $crate::cmp::PartialEq, E: ~const $crate::cmp::PartialEq> PartialEq for Result<T, E>impl PartialEq for Alignmentimpl PartialEq for DebugAsHeximpl<F> PartialEq for fn(_: T) -> Retimpl<T, U> PartialEq for [T]impl PartialEq for ParseBoolErrorimpl PartialEq for SearchStepimpl PartialEq for Ipv4Addrimpl PartialEq for TryFromFloatSecsErrorimpl PartialEq for IpAddrimpl<T> PartialEq for NonZero<T>impl PartialEq for IpAddrimpl PartialEq for Alignmentimpl PartialEq for neverimpl PartialEq for AsciiCharimpl PartialEq for SocketAddrV4impl PartialEq for CpuidResultimpl<T: PointeeSized> PartialEq for *const Timpl<A, B: PointeeSized> PartialEq for &mut Aimpl PartialEq for [u8]impl PartialEq for Location<'_>impl PartialEq for Orderingimpl<A, B: PointeeSized> PartialEq for &mut Aimpl PartialEq for ByteStrimpl<'a> PartialEq for PhantomContravariantLifetime<'a>impl PartialEq for &strimpl<T> PartialEq for PhantomContravariant<T>impl<N: usize> PartialEq for ByteStrimpl PartialEq for PhantomPinnedimpl<T: PartialEq + Copy> PartialEq for Cell<T>impl PartialEq for RangeFullimpl PartialEq for CharTryFromErrorimpl<Idx: ~const $crate::cmp::PartialEq> PartialEq for RangeTo<Idx>impl PartialEq for CharCaseimpl<T: ~const $crate::cmp::PartialEq> PartialEq for Bound<T>impl PartialEq for FromBytesUntilNulErrorimpl PartialEq for RawWakerimpl<T: ?Sized + PartialEq> PartialEq for ManuallyDrop<T>impl PartialEq for SimdAlignimpl PartialEq for LayoutErrorimpl<T, N: usize> PartialEq for Simd<T, N>impl<Idx: ~const $crate::cmp::PartialEq> PartialEq for Range<Idx>impl PartialEq for ()impl<Idx: $crate::cmp::PartialEq> PartialEq for RangeToInclusive<Idx>impl<T> PartialEq for Discriminant<T>impl PartialEq for charimpl<T, U> PartialEq for Exclusive<T>impl PartialEq for u8impl PartialEq for Signimpl PartialEq for u32impl<H> PartialEq for BuildHasherDefault<H>impl PartialEq for u128impl<T: PointeeSized> PartialEq for NonNull<T>impl PartialEq for Utf8Errorimpl PartialEq for TryFromIntErrorimpl PartialEq for Assumeimpl PartialEq for i8impl<'a> PartialEq for Utf8Pattern<'a>impl PartialEq for i32impl<T, U, N: usize> PartialEq for [T; N]impl PartialEq for IpAddrimpl PartialEq for Durationimpl PartialEq for i128impl<T, U, N: usize> PartialEq for [T]impl PartialEq for Ipv6MulticastScopeimpl PartialEq for f32impl<T, U, N: usize> PartialEq for &[T]impl PartialEq for Ipv6Addrimpl<Dyn: PointeeSized> PartialEq for DynMetadata<Dyn>impl PartialEq for f128impl<T, U, N: usize> PartialEq for &mut [T]impl PartialEq for SocketAddrimpl<T: ~const PartialEq> PartialEq for (T)impl PartialEq for Localityimpl PartialEq for ByteStrimpl<T: ~const PartialEq> PartialEq for Option<T>impl<F: FnPtr> PartialEq for Fimpl PartialEq for &[u8]impl<'a> PartialEq for PhantomCovariantLifetime<'a>impl PartialEq for ByteStrimpl<T> PartialEq for PhantomCovariant<T>impl<N: usize> PartialEq for [u8; N]impl<T: $crate::cmp::PartialEq> PartialEq for Saturating<T>impl<T: PointeeSized> PartialEq for PhantomData<T>impl<T: PartialEq> PartialEq for OnceCell<T>impl<Y: $crate::cmp::PartialEq, R: $crate::cmp::PartialEq> PartialEq for CoroutineState<Y, R>impl PartialEq for ParseCharErrorimpl<Idx: ~const $crate::cmp::PartialEq> PartialEq for RangeFrom<Idx>impl PartialEq for TryFromCharErrorimpl<Idx: $crate::cmp::PartialEq> PartialEq for RangeToInclusive<Idx>impl PartialEq for FromBytesWithNulErrorimpl PartialEq for Layoutimpl PartialEq for ParseFloatErrorimpl<A, B: PointeeSized> PartialEq for &Aimpl<A, B: PointeeSized> PartialEq for &Aimpl<Ptr: Deref, Q: Deref> PartialEq for Pin<Ptr>impl<Idx: ~const $crate::cmp::PartialEq> PartialEq for RangeFrom<Idx>impl<T: $crate::cmp::PartialEq> PartialEq for Wrapping<T>impl PartialEq for Orderingimpl PartialEq for Errorimpl PartialEq for FpCategoryimpl PartialEq for FormattingOptionsimpl PartialEq for GetDisjointMutErrorimpl PartialEq for IntErrorKindimpl PartialEq for strimpl PartialEq for CStrimpl<'a> PartialEq for Utf8Chunk<'a>impl PartialEq for Ipv6Addrimpl<T: $crate::cmp::PartialEq> PartialEq for Poll<T>impl<T: $crate::cmp::PartialEq + PointeeSized> PartialEq for TraitImpl<T>impl PartialEq for AtomicOrderingimpl PartialEq for Ipv4Addrimpl PartialEq for AddrParseErrorimpl PartialEq for ByteStrimpl PartialEq for SocketAddrV6impl<T, N: usize> PartialEq for Mask<T, N>impl<T: PointeeSized> PartialEq for *mut Timpl PartialEq for ByteStrimpl PartialEq for ParseIntErrorimpl<T: ~const $crate::cmp::PartialEq> PartialEq for Reverse<T>impl PartialEq for Infallibleimpl PartialEq for strimpl PartialEq for boolimpl<'a> PartialEq for PhantomInvariantLifetime<'a>impl<N: usize> PartialEq for ByteStrimpl PartialEq for usizeimpl<T> PartialEq for PhantomInvariant<T>impl<N: usize> PartialEq for &[u8; N]impl PartialEq for u16impl<B: ~const $crate::cmp::PartialEq, C: ~const $crate::cmp::PartialEq> PartialEq for ControlFlow<B, C>impl<T: ?Sized + PartialEq> PartialEq for RefCell<T>impl PartialEq for u64impl<Idx: ~const $crate::cmp::PartialEq> PartialEq for Range<Idx>impl PartialEq for DecodeUtf16Errorimpl PartialEq for isizeimpl<Idx: ~const $crate::cmp::PartialEq> PartialEq for RangeInclusive<Idx>impl PartialEq for CStrimpl PartialEq for i16impl PartialEq for TypeIdimpl PartialEq for i64impl<T, U, N: usize> PartialEq for [T; N]