Go has strictly comparable semantics for values used as map keys . Thus, you cannot define your own hash code and equality functions for map keys, as can be done in many other languages.
However, consider the following workaround. Instead of using instances of the structure directly as keys, use a derived attribute of the structure, which by its nature can be used as a key and has the desired semantics of equality. It is often easy to get an integer or string value as a hash code that serves as an identifier for an instance.
For instance:
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 issue with this approach. In the above example, if you change the field a instance will no longer be used as a hash key, because its identifier has changed.
source share