加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

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

发布时间:2020-12-16 09:22:14 所属栏目:大数据 来源:网络整理
导读:在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的元素).我以前从未见过这样的东西.它的
在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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读