Skip to content

HashMap docs don't mention {Eq, Hash} consistency #23320

Closed
@apasel422

Description

@apasel422

While it may not be possible to enforce this at the type level, the docs for HashMap (and HashSet) should specify that its key type's {Eq, Hash} implementations must be consistent for the map to have reasonable behavior. The exact requirement is

k1 == k2 -> hash(k1) == hash(k2)

This is always the case for derived implementations, but the following example is nonsensical if Foo is used as a HashMap key:

#[derive(Hash)]
struct Foo(u32, u32);

impl PartialEq for Foo {
    fn eq(&self, other: &Foo) -> bool { self.0 == other.0 }
}

impl Eq for Foo {}

There could additionally be some kind of debug-level assertion of this behavior, or possibly a lint that checks to make sure that the fields that are referenced in PartialEq::eq and Hash::hash are consistent. The lint wouldn't be perfect, but could be useful.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions