为什么不能将切片用作Go地图中的键,几乎可以将数组用作键? [英] Why can't Go slice be used as keys in Go maps pretty much the same way arrays can be used as keys?

查看:141
本文介绍了为什么不能将切片用作Go地图中的键,几乎可以将数组用作键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不能将切片(Go数组的一个实现)用作Go地图中的键与数组可以用作键的方式相同?

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?

推荐答案

这是Nigel Tao的答案,从 https://groups.google.com/forum/#!topic/golang-nuts/zYlx6sR4F8Y

Here's Nigel Tao's answer from https://groups.google.com/forum/#!topic/golang-nuts/zYlx6sR4F8Y:


其中一个原因数组是值类型。如果 a0 是一个 [N] int (一个
数组)然后执行

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

a1 := a0
a1[0] = 0

根本不会影响 a0 [0]

比较,切片指的是底层数组。复制切片
值是O(1)而不是O(长度)。如果 s0 是一个 [] int (一个切片)
然后执行

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

将影响什么 s0 [0] 是。

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.

这篇关于为什么不能将切片用作Go地图中的键,几乎可以将数组用作键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆