Home > Backend Development > Golang > How Can I Implement Custom Equality for Map Keys in Go?

How Can I Implement Custom Equality for Map Keys in Go?

Susan Sarandon
Release: 2024-12-08 14:32:17
Original
341 people have browsed it

How Can I Implement Custom Equality for Map Keys in Go?

Custom Map Keys with User-Defined Equality in Go

In Go, maps employ strict comparable semantics for map keys. This means programmers cannot implement their own hash functions and equality operations for map keys as they can in other languages.

To address this limitation, consider an alternative approach. Instead of utilizing struct instances as keys directly, employ a derived attribute of the struct that serves as a suitable map key and adheres to the desired equality semantics. In many cases, it's feasible to derive an integer or string value as a hash code representing the identity of an instance.

It's crucial to ensure that collisions in the derived hash code only occur when they indicate genuine semantic identity of the stored value. This means that corresponding values should be interchangeable.

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"
Copy after login

However, be cognizant of immutability concerns when using this approach. If you modify the a field in the example above, the instance can no longer serve as a hash key because its identity has changed.

The above is the detailed content of How Can I Implement Custom Equality for Map Keys in Go?. 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