Complex datatypes as keys in maps in Go

后端 未结 1 1476
感情败类
感情败类 2021-02-14 14:19

I\'m trying to create a map in Go that is keyed by big integers. Effective Go explicitly says that:

Structs, arrays and slices cannot be used as map keys,

相关标签:
1条回答
  • 2021-02-14 14:52

    The rules about equality are going to change soon. From the 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.)

    However, even with this rules, you can not use *BigInt as key, since it contains a slice. Also note, that it is not possible in Go to write a custom equality operator (neither it is possible to override any other operator). But that's actually a strength of Go in my opinion - things are just simpler without it.

    So, you will have to use strings for your keys. The strings however do not need to be formatted in decimal (or any other format) as long as you do not want to print them. So the fastest way is probably to use the Bytes() method (which will also discard the sign, make sure to include that separately in your string).

    0 讨论(0)
提交回复
热议问题