gpt4 book ai didi

go - 复杂数据类型作为 Go map 中的键

转载 作者:IT老高 更新时间:2023-10-28 13:09:21 25 4
gpt4 key购买 nike

我正在尝试在 Go 中创建一个以大整数为键的 map 。 Effective Go 明确表示:

Structs, arrays and slices cannot be used as map keys, because equality is not defined on those types.

这是有道理的。我当然可以将大整数转换为字符串并将字符串用作键,但我在这里寻找更通用的解决方案。我可以将我的结构包装成实现相等函数的东西(接口(interface)?)并改用它吗?

当然不起作用的示例代码:

package main                                                                                                           

import (
"big"
"fmt"
)

func main() {
one1 := big.NewInt(1)
one2 := big.NewInt(1)

hmap := make(map[*big.Int] int)
hmap[one1] = 2
_, exists := hmap[one2]
fmt.Printf("Exists=%v\n", exists)
}

最佳答案

关于平等的规则很快就会改变。来自 Go 1 plan :

Go 1 will define equality on struct and array values composed from fields on which equality is also defined (element-wise comparison). It will remove equality on function and map values except for comparison with nil. Go 1 will continue to exclude equality for slices. (In the general case it is infeasible.)

但是,即使使用此规则,您也不能使用 *BigInt 作为键,因为它包含一个 slice 。另请注意,在 Go 中不可能编写自定义相等运算符(也不可能覆盖任何其他运算符)。但在我看来,这实际上是 Go 的优势——没有它,事情会变得更简单。

因此,您将不得不为您的键使用字符串。但是,只要您不想打印字符串,就不需要将其格式化为十进制(或任何其他格式)。所以最快的方法可能是使用 Bytes() 方法(它也会丢弃符号,确保在你的字符串中单独包含它)。

关于go - 复杂数据类型作为 Go map 中的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8071383/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com