gpt4 book ai didi

arrays - 为什么 Go slice 不能像数组用作键一样用作 Go 映射中的键?

转载 作者:IT王子 更新时间:2023-10-29 01:52:36 24 4
gpt4 key购买 nike

为什么 Go slice (它是 Go 数组的一种实现)不能像数组用作键一样用作 Go 映射中的键?

最佳答案

这是 Nigel Tao 来自 https://groups.google.com/forum/#!topic/golang-nuts/zYlx6sR4F8Y 的回答:

One reason is that arrays are value types. If a0 is an [N]int (an array) then doing

a1 := a0
a1[0] = 0

will not affect a0[0] at all.

In comparison, slices refer to an underlying array. Copying a slice value is O(1) instead of O(length). If s0 is an []int (a slice) then doing

s1 := s0
s1[0] = 0

will affect what s0[0] is.

http://play.golang.org/p/TVkntIsLo8

Map keys need some notion of equality. For arrays, this is simply element-wise equality. For slices, there is more than one way to define equality: one is element-wise equality, another is referring to the same array backing store. Furthermore, does map insertion need to make an (expensive) copy of the entire backing array? Copying would probably be less surprising, but it is inconsistent with what assignment does.

What should this code snippet print?

m := make(map[[]int]bool)
s0 := []int{6, 7, 8}
s1 := []int{6, 7, 8}
s2 := s0
m[s0] = true
s2[0] = 9
println(m[s0])
println(m[s1])
println(m[s2])

Different programmers can have different expectations. To avoid confusion, we have simply decided not to allow slices as map keys for now.

关于arrays - 为什么 Go slice 不能像数组用作键一样用作 Go 映射中的键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37900696/

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