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

标签 arrays go initialization slice

pub quiz 中通过 Dave Cheney 我遇到了以下结构:

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,将索引 5 处的元素设置为 0)。我以前从未见过这样的事情。它的用例是什么?为什么不直接设置特定索引?

最佳答案

composite literals可以选择提供键(在数组和 slice 文字的情况下为索引)。

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.

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

您可以使用它来:

  • 如果数组/slice 有许多零值和只有几个非零值,则更紧凑地初始化数组和 slice

  • 在枚举元素时跳过(“跳过”)连续部分,跳过的元素将用零值初始化

  • 指定前几个元素,并仍然指定您希望数组/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}

另一个例子:让我们创建一个 slice 来判断某一天是否是周末;周一为 0,周二为 1,...周日为 6:

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

或者更好的是,您甚至可以省略第二个索引 (6),因为它将隐式为 6(之前的 +1):

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

关于arrays - golang 数组初始化中的键控项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36302441/

相关文章:

go - 如何读取固定数量的字节?

go - 无法让 Oauth2 TokenSource 刷新从存储中检索到的 token

c++11 - std::array 的默认初始化?

arrays - React 重新渲染循环

javascript - 使用整数键创建关联数组

go - 如何将多个返回值传递给可变参数函数?

ruby 方法 : how to return an usage string when insufficient arguments are given

arrays - 当我在 main 函数外初始化结构成员时,为什么这个 c 程序会出错?

c++ - 将数组的次对角线上的元素相乘。宝兰C

python - 查找所有字符串拆分组合