Home > Backend Development > Golang > How Can I Implement Custom Key Equality for Go Maps?

How Can I Implement Custom Key Equality for Go Maps?

Barbara Streisand
Release: 2025-01-02 21:31:39
Original
928 people have browsed it

How Can I Implement Custom Key Equality for Go Maps?

Custom Key Equality for Go Maps

When creating a map in Go, you can use any type as a key as long as it implements the comparable interface. By default, Go uses the builtin equality operator (==) for comparing keys. However, there may be instances where you want to define your own equality criteria.

Example

Consider the following custom key type:

type Key struct {
    a *int
}
Copy after login

To compare two instances of Key, you want to use your own Equal function:

func Equal(x Key, y Key) bool {
    return *x.a == *y.a
}
Copy after login

Workaround

Unfortunately, Go doesn't allow you to specify custom hashing or equality functions for map keys. Instead, you can use the following workaround:

  1. Derive a Key Attribute: Instead of using the Key struct directly as a key, derive an attribute (e.g., integer or string) that serves as the identity for the key. Ensure that collisions only occur for semantically identical keys.
  2. Implement Hash Function: Create a method on Key that calculates the derived attribute and returns it as an integer (for hashing).
func (k *Key) HashKey() int {
    return *(*k).a
}
Copy after login

Example Usage

Using the example above, the map would be:

k1, k2 := Key{intPtr(1)}, Key{intPtr(2)}
m := map[int]string{}
m[k1.HashKey()] = "one"
m[k2.HashKey()] = "two"
Copy after login

Precautions

Remember that this approach relies on the immutability of the derived key attribute. If any fields in the Key struct change, the identity of the key changes and it will not work as expected.

The above is the detailed content of How Can I Implement Custom Key Equality for Go Maps?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template