Looking for HashMaps with internal keys

I'm looking for a variant of a HashMap that has internal keys. "Internal keys" is a term I just invented, perhaps this idea has a real name?

Anyway, what I mean is that I have a struct, for example

struct Item {
    name: String,
    // other data ...
}

Ideally I would store my items in a "not-quite HashMap" that uses the existing name as the key instead of a separate value.

Does such a thing already exist in some crate?

You may be looking for a HashSet, where a custom hash is computed from just the name field. Be sure to also implement a custom PartialEq that also only uses the name field.

You may be looking for a HashSet, where Hash is implemented directly (not derived) for your Item struct, and is computed from just the name field. Be sure to also implement PartialEq for Item and this must also only use the name field.

3 Likes

And if this is a problem for you, you can use a new type.

// Implement `Hash` and `PartialEq` based on just the `name` field for
// this instead of for `Item`
pub struct Entry(pub Item);

And probably also

impl Borrow<str> for Entry {

which means other traits like PartialOrd, etc, also have to be based on just the name field.

Example.

2 Likes

You can use hashbrown::HashMap::<Item, ()>::raw_entry if you find newtype being too messy.

That's a neat idea, thanks. It hadn't occurred to me to use a HashMap like that

1 Like