arrays – golang数组初始化中的键控项

在Dave Cheney的 pub quiz中,我遇到了以下构造:

a := [...]int{5,4: 1,2: 3,2,1: 4}
fmt.Println(a)

>> [5 4 3 2 1 0]

(Playground Link)

看起来你可以在数组的初始化字段中使用键(4:1,0表示索引4到1的set元素,索引5到0的元素).我以前从未见过这样的东西.它的用例是什么?为什么不直接设置特定索引?

解决方法

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.

元素获取未指定其值的元素类型的零值.

你可以用它来:

>如果数组/切片具有许多零值且只有几个非零值,则更紧凑地初始化数组和切片
>枚举元素时跳过(“跳过”)连续的部分,跳过的元素将使用零值初始化
>指定前几个元素,并仍指定希望数组/切片具有的长度(最大索引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(前一个):

weekend := []bool{5: true,true} // The rest will be false

相关文章

类型转换 1、int转string 2、string转int 3、string转float ...
package main import s "strings" import...
类使用:实现一个people中有一个sayhi的方法调用功能,代码如...
html代码: beego代码:
1、读取文件信息: 2、读取文件夹下的所有文件: 3、写入文件...
配置环境:Windows7+推荐IDE:LiteIDEGO下载地址:http:...