PartialEq and Eq
Partial equality & Total equality.
Derivable: ✅
// Copyright 2025 Google LLC // SPDX-License-Identifier: Apache-2.0 #[derive(PartialEq, Eq)] pub struct User { name: String, favorite_number: i32 } fn main() { let alice = User { name: "alice".to_string(), favorite_number: 1_000_042 }; let bob = User { name: "bob".to_string(), favorite_number: 42 }; dbg!(alice == alice); dbg!(alice == bob); }
-
Equality-related methods. If a type implements
PartialEqthen you can use the==/!=operator with that type. -
A type can’t implement
Eqwithout implementingPartialEq. -
Reminder: Partial means “there are invalid members of this set for this function.”
This doesn’t mean that equality will panic, or that it returns a result, just that there may be values that may not behave as you expect equality to behave.
For example, with floating point values
NaNis an outlier:NaN == NaNis false, despite bitwise equality.PartialEqexists to separate types likef32/f64from types with Total Equality. -
You can implement
PartialEqbetween different types, but this is mostly useful for reference/smart pointer types.