golang数组初始化中的键值项 [英] Keyed items in golang array initialization
问题描述
在 Dave Cheney 的 pub quiz 中,我遇到了以下结构:
In a pub quiz by Dave Cheney I came across the following construct:
a := [...]int{5, 4: 1, 0, 2: 3, 2, 1: 4}
fmt.Println(a)
>> [5 4 3 2 1 0]
(游乐场链接)
您似乎可以在数组的初始化字段中使用键(4: 1, 0
表示将索引 4 处的元素设置为 1,将索引 5 处的元素设置为 0).我以前从未见过这样的事情.它的用例是什么?为什么不直接设置特定的索引?
It seems you can use keys in the initialization fields of an array (4: 1, 0
means set element at index 4 to 1, element at index 5 to 0). I have never seen something like this before. What is its use case? Why not set the particular index directly?
推荐答案
在 复合文字中可以选择提供键(数组和切片文字的索引).
In composite literals the key (index in case of array and slice literals) can be optionally provided.
对于数组和切片字面量,以下规则适用:
For array and slice literals the following rules apply:
- 每个元素都有一个关联的整数索引,用于标记其在数组中的位置.
- 具有键的元素使用该键作为其索引;键必须是常量整数表达式.
- 没有键的元素使用前一个元素的索引加一.如果第一个元素没有键,则其索引为零.
元素获取未指定值的元素类型的零值.
Elements get the zero value of the element type whose value is not specified.
你可以用它来:
如果数组/切片有许多零值和几个非零值,则更紧凑地初始化数组和切片
more compactly initialize arrays and slices if the array/slice has many zero values and just a few non-zero values
枚举元素时跳过(跳过")连续部分,跳过的元素将被初始化为零值
skip ("jump over") contiguous parts when enumerating elements, and the skipped elements will be initialized with the zero values
指定前几个元素,并仍然指定您希望数组/切片具有的长度(最大索引 + 1):
specify the first couple of elements, and still specify the length (max index + 1) you want the array/slice to have:
a := []int{10, 20, 30, 99:0} // Specify first 3 elements and set length to 100
规范还包含一个示例:创建一个数组来判断一个字符是否为元音.这是初始化数组的一种非常紧凑和健谈的方式:
The spec also contains an example: create an array which tells if a character is a vowel. This is a very compact and talkative way to initialize the array:
// vowels[ch] is true if ch is a vowel
vowels := [128]bool{'a': true, 'e': true, 'i': true, 'o': true, 'u': true, 'y': true}
另一个例子:让我们创建一个切片来判断一天是否是周末;星期一是 0,星期二是 1,... 星期日是 6:
Another example: let's create a slice which tells if a day is weekend; Monday being 0, Tuesday being 1, ... and Sunday being 6:
weekend := []bool{5: true, 6: true} // The rest will be false
或者更好的是,您甚至可以省略第二个索引 (6
),因为它会隐含为 6
(之前的 +1):
Or even better, you can even omit the 2nd index (6
) as it will be implicitly 6
(previous +1):
weekend := []bool{5: true, true} // The rest will be false
这篇关于golang数组初始化中的键值项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!