What is the design reason behind Hashmap::get requiring K:Borrow<Q> instead of K:Eq<Q>?

I find it really hard to use &str tuple to look up String tuple key. I've found some stackoverflow post and it's really complex.
While this specific case could be easily worked around by creating HashMap<String, HashMap<String, V>>, if the key was a newtype struct then the workaround can't be applied.
I'm curious about the downside of HashMap::get requiring K: Eq<Q> or Q: Eq<K> - if this was the constraint of get method it would be much easier to query the map with borrowed values.
Someone told me that erroneous Eq impl can break logical correctness, but incorrect Borrow impl can break the logical correctness too(ex: String newtype where it always returns "static string" for Borrow).

Eq doesn't have a type parameter, it corresponds to PartialEq<Self>.

For an example of K: PartialEq<Q> or Q: PartialEq<K> not being adequate for HashMap, consider this playground which has no erroneous implementations (no violations of any trait's logical expectations).

You are looking for the Equivalent trait.

1 Like