Custom Key and Equality for Go Maps
In Go, maps use strict equality for comparing keys. This means that to use a custom type as a map key, it must implement the standard equality operator (==). However, there are workarounds to this limitation.
Using Derived Keys
Instead of using struct instances as keys directly, consider using a derived attribute that serves as an identity for the instance. This attribute should be intrinsically usable as a key and have the desired equality semantics. Common options include integer hash codes or string representations.
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"
Caution: It's crucial to ensure that derived keys only collide when they truly represent semantic identity. Modifying fields in a derived key invalidates its use as a key because its identity has changed.
The above is the detailed content of How Can I Use Custom Types as Keys in Go Maps?. For more information, please follow other related articles on the PHP Chinese website!