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

arrays – golang数组初始化中的键控项,第1张

概述在Dave Cheney的 pub quiz中,我遇到了以下构造: a := [...]int{5, 4: 1, 0, 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 vowelvowels := [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
总结

以上是内存溢出为你收集整理的arrays – golang数组初始化中的键控项全部内容,希望文章能够帮你解决arrays – golang数组初始化中的键控项所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1265597.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-08
下一篇 2022-06-08

发表评论

登录后才能评论

评论列表(0条)

保存