使用用户定义的键与用户定义的相等来转换地图? [英] Go map with user-defined key with user-defined equality?

查看:107
本文介绍了使用用户定义的键与用户定义的相等来转换地图?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我在Go中有一个结构类型,我想用它作为地图中的一个键,但是我不希望使用Go的内置相等性操作。建立这样一个映射的最好方法是什么?



对于一个具体的例子,这里是我的键类型和相等操作:

 类型键结构{
a * int
}

func Equal(x Key,y Key)bool {
返回* xa == * ya
}

如何构建一个使用 Equal 用于键比较?

解决方案

Go has 用作地图键的值的严格可比语义。因此,您无法像使用其他许多语言一样为映射键定义您自己的散列码和相等函数。然而,请考虑以下解决方法。不要直接使用结构实例作为键,而应使用结构的派生属性,该结构本质上可用作键,并且具有您所需的相等语义。通常很容易将一个整数或字符串值作为一个哈希码来作为一个实例的身份。



例如:

 类型键结构{
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

当然,不变性是这种方法的一个关键问题。在上面的示例中,如果修改字段 a ,那么该实例不能再用作散列键,因为其标识已更改。


Suppose I have a struct type in Go that I want to use as a key in a map, but I don't want to use Go's builtin equality operation. What's the best way to build such a map?

For a concrete example, here is my key type and equality operation:

type Key struct {
    a *int
}

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

How can I build a map that uses Equal for key comparison?

解决方案

Go has strict comparable semantics for values used as map keys. As such, you cannot define your own hash code and equality functions for map keys as you can in many other languages.

However, consider the following workaround. Instead of using the struct instances directly as a keys, use a derived attribute of the struct which is intrinsically usable as a key and has the equality semantics you desire. Often it is simple to derive an integer or string value as a hash code which serves as the identity for an instance.

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"

Of course, immutability is a critical concern with this approach. In the example above, if you modify the field a then the instance can no longer be used as a hash key because its identity has changed.

这篇关于使用用户定义的键与用户定义的相等来转换地图?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆