Home >Backend Development >Golang >How Can I Use User-Defined Structs as Keys in Go Maps?
Go Maps with User-Defined Keys and Custom Equality
Implementing a Go map with user-defined keys involves adhering to specific equality rules. Unfortunately, Go's built-in equality operations cannot be customized for map keys. However, an effective workaround exists.
Instead of directly using the struct instances as keys, consider deriving a unique attribute that can serve as an intrinsic key and aligns with your desired equality semantics. For instance, you could derive an integer or string value representing the instance's identity.
It's crucial to ensure that key collisions only occur when the corresponding values represent true semantic identity. This ensures that interchangeable values are correctly mapped.
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"
Remember, this approach requires immutable keys. Modifying the field in the above example invalidates the key's identity, rendering it unsuitable as a hash key.
The above is the detailed content of How Can I Use User-Defined Structs as Keys in Go Maps?. For more information, please follow other related articles on the PHP Chinese website!