Having a manual PartialEq
implementation for types with a derived Hash
can lead to inconsistencies. The contract k1
== k2 ⇒ hash(k1) == hash(k2)
must always hold. Inconsistencies can cause undefined behaviors, especially when these types are used in
collections such as HashMap
.
Code examples
Noncompliant code example
#[derive(Hash)]
struct Foo;
impl PartialEq for Foo {
fn eq(&self, other: &Self) -> bool {
// Some custom equality logic
true // Noncompliant
}
}
Compliant solution
#[derive(Hash, PartialEq)]
struct Foo;