the*_*Jun 2 arrays dictionary go slice
为什么 Go 切片(Go 数组的实现)不能用作 Go 映射中的键,就像数组用作键一样?
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
a0
is an[N]int
(an array) then doingRun Code Online (Sandbox Code Playgroud)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 doingRun Code Online (Sandbox Code Playgroud)s1 := s0 s1[0] = 0
will affect what
s0[0]
is.http://play.golang.org/p/TVkntIsLo8
映射键需要一些相等的概念。对于数组来说,这只是元素之间的相等。对于切片,定义相等性的方法不止一种:一种是按元素相等,另一种是引用相同的数组后备存储。此外,映射插入是否需要制作整个后备数组的(昂贵的)副本?复制可能不会那么令人惊讶,但它与赋值的作用不一致。
该代码片段应该打印什么?
Run Code Online (Sandbox Code Playgroud)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])
不同的程序员可能有不同的期望。为了避免混淆,我们只是决定暂时不允许切片作为映射键。