Why can't Go slice (which is an implementation of Go arrays) be used as keys in Go maps pretty much the same way arrays can be used as keys?
2条回答 默认 最新
dongzhong5756 2016-06-18 20:24关注Here's Nigel Tao's answer from https://groups.google.com/forum/#!topic/golang-nuts/zYlx6sR4F8Y:
One reason is that arrays are value types. If
a0is an[N]int(an array) then doinga1 := a0 a1[0] = 0will 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
s0is an[]int(a slice) then doings1 := s0 s1[0] = 0will 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.
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报