Home > Backend Development > Golang > How Can I Use Custom Types as Keys in Go Maps?

How Can I Use Custom Types as Keys in Go Maps?

Susan Sarandon
Release: 2024-12-12 13:57:10
Original
118 people have browsed it

How Can I Use Custom Types as Keys in Go Maps?

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

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!

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