Go has strict comparable semantics for values used as map keys. As such, you cannot define your own hash code and equality functions for map keys as you can in many other languages.
However, consider the following workaround. Instead of using the struct instances directly as a keys, use a derived attribute of the struct which is intrinsically usable as a key and has the equality semantics you desire. Often it is simple to derive an integer or string value as a hash code which serves as the identity for an instance.
Importantly, the keys should only collide if they truly represent semantic identity of the value being stored. That is, corresponding values should be truly interchangeable.
For example:
type Key struct {
a *int
}
func (k *Key) HashKey() int {
return *(*k).a
}
k1, k2 := Key{intPtr(1)}, Key{intPtr(2)}
m := map[int]string{}
m[k1.HashKey()] = "one"
m[k2.HashKey()] = "two"
// m = map[int]string{1:"one", 2:"two"}
m[k1.HashKey()] // => "one"
Of course, immutability is a critical concern with this approach. In the example above, if you modify the field a
then the instance can no longer be used as a hash key because its identity has changed.