I would like to store values in some container indexed by a sub-property; i.e. I wish to store structs where one of the fields contains the key.
struct MyData {
key: K,
...
}
Possibilities:
- Use
HashMap<K, MyData> and just store the key twice.
- Remove
key from MyData — but there are reasons MyData wants to know about the key
- Define struct
MyDataExceptKey and use in the HashMap, then recreate MyData when extracting… but this is really silly.
- Use
HashSet<MyData> and special implementations of PartialEq and Hash which only compare based on MyData's key. (This means values in the set are immutable, which is okay for my use case.) [I’ve used this option with C++'s std::set/map before.]
The last option is the route I’ve gone, except that I’ve created a wrapper library so that the user’s type doesn’t itself have to have modified eq and hash implementations. (I was planning on releasing the library when it’s working.)
Problem: neither HashSet nor HashMap provides a way to get the key (except by iterating). Can this be changed?
As an aside, my wrapper API could almost be used as a generalisation of HashMap and HashSet; the exception being that values couldn’t be modified in place without a run-time check that the key didn’t change (and in any case, this isn’t possible when building on top of HashSet or HashMap).