这个数组初始化语法是什么意思?(带有键的元素)

huangapple go评论83阅读模式
英文:

What this array init syntax mean? (elements with keys)

问题

我最近找到了下面的代码:

var noEscape = [256]bool{
    'A': true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
    'a': true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
    '0': true, true, true, true, true, true, true, true, true, true,
    '-': true,
    '.': true,
    '_': true,
    '~': true,
}

我理解这个[N]bool默认情况下会用N个false(零)进行初始化。如果在冒号后面指定了索引,那么可以为索引指定值(包括索引本身)。这在哪里有描述?在示例中可以使用哪些类型作为索引值(示例中使用了char)?

英文:

I recently found the code below:

var noEscape = [256]bool{
	'A': true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
	'a': true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true, true,
	'0': true, true, true, true, true, true, true, true, true, true,
	'-': true,
	'.': true,
	'_': true,
	'~': true,
}

I understand that this [N]bool is initialized with N false (zeros) by default. And if the index followed by a colon is specified values can are defined form the index (inclusive). Where is it described? What types can be used as an index value (there is a char in the example)?

答案1

得分: 6

对于数组或切片字面量,索引值必须是常量。根据“复合字面量”的文档:

  • 每个元素都有一个关联的整数索引,标记其在数组中的位置。
  • 使用键的元素将键作为其索引;键必须是一个常量整数表达式。
  • 没有键的元素使用前一个元素的索引加一。如果第一个元素没有键,则其索引为零。

示例中的字面字符是无类型的常量,只是恰好被写成单个符文字面量。如果你将这些值分配给一个变量以用作索引,代码将无法编译。

英文:

For an array or slice literal, the index values must be constants. From the docs on "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.

The literal characters in the example are untyped constants, which just happen to be written as a single rune literal. If you were to assign any of those values to a variable to use as the index, the code would not compile.

huangapple
  • 本文由 发表于 2015年12月31日 21:57:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/34547457.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定