golang 数组初始化中的键控项
Keyed items in golang array initialization
在 Dave Cheney 的 pub quiz 中,我遇到了以下结构:
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)。我以前从未见过这样的事情。它的用例是什么?为什么不直接设置特定索引?
如果你的数组索引是稀疏的,它比 {1,0,0,0,0,2,0,0,0,0,3}
等更短,也比多个赋值行更短,所以我猜这就是用例。
我以前从未在任何地方见过这种语法。
在 composite literals 中,可以选择提供键(数组和切片文字的索引)。
For array and slice literals the following rules apply:
- Each element has an associated integer index marking its position in the array.
- An element with a key uses the key as its index; the key must be a constant integer expression.
- An element without a key uses the previous element's index plus one. If the first element has no key, its index is zero.
元素获取未指定值的元素类型的零值。
您可以使用它来:
如果 array/slice 有许多零值和只有几个非零值
,则更紧凑地初始化数组和切片
枚举元素时跳过(“跳过”)连续部分,跳过的元素将用零值初始化
指定前几个元素,并仍然指定您希望 array/slice 具有的长度(最大索引 + 1):
a := []int{10, 20, 30, 99:0} // Specify first 3 elements and set length to 100
规范还包含一个示例:创建一个数组来判断字符是否为元音。这是一种非常紧凑和健谈的初始化数组的方式:
// 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:
weekend := []bool{5: true, 6: true} // The rest will be false
或者更好的是,您甚至可以省略第二个索引 (6
),因为它将隐含地 6
(previous +1):
weekend := []bool{5: true, true} // The rest will be false
在 Dave Cheney 的 pub quiz 中,我遇到了以下结构:
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)。我以前从未见过这样的事情。它的用例是什么?为什么不直接设置特定索引?
如果你的数组索引是稀疏的,它比 {1,0,0,0,0,2,0,0,0,0,3}
等更短,也比多个赋值行更短,所以我猜这就是用例。
我以前从未在任何地方见过这种语法。
在 composite literals 中,可以选择提供键(数组和切片文字的索引)。
For array and slice literals the following rules apply:
- Each element has an associated integer index marking its position in the array.
- An element with a key uses the key as its index; the key must be a constant integer expression.
- An element without a key uses the previous element's index plus one. If the first element has no key, its index is zero.
元素获取未指定值的元素类型的零值。
您可以使用它来:
如果 array/slice 有许多零值和只有几个非零值
,则更紧凑地初始化数组和切片枚举元素时跳过(“跳过”)连续部分,跳过的元素将用零值初始化
指定前几个元素,并仍然指定您希望 array/slice 具有的长度(最大索引 + 1):
a := []int{10, 20, 30, 99:0} // Specify first 3 elements and set length to 100
规范还包含一个示例:创建一个数组来判断字符是否为元音。这是一种非常紧凑和健谈的初始化数组的方式:
// 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:
weekend := []bool{5: true, 6: true} // The rest will be false
或者更好的是,您甚至可以省略第二个索引 (6
),因为它将隐含地 6
(previous +1):
weekend := []bool{5: true, true} // The rest will be false