Go to map with user-defined key with user-defined equality?

Suppose I have a type of structure in Go that I want to use as a key on the map, but I don't want to use the Go operation built into the equality. What is the best way to build such a map?

For a specific example, here is my key type and equality operation:

type Key struct { a *int } func Equal(x Key, y Key) bool { return *xa == *ya } 

How to create a map using Equal to compare keys?

+11
source share
2 answers

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.

+12
source

This is not possible in Go. There is no overload of operators or the Equality method that you can override (due to the lack of inheritance from a common base class, as in .NET, which your example reminds me of). This answer contains more information about equality comparisons, if you're interested; Is it possible to define equality for named types / structures?

As mentioned in the comments, if you want to do something like this work, I would recommend using the object property as the key. You can define equality based on how you set the value of this property (for example, it could be a checksum of object bytes or something else if you are looking for member equality).

+3
source

Source: https://habr.com/ru/post/985223/


All Articles