翻译进度
3
分块数量
0
参与人数

Index expressions

这是一篇协同翻译的文章,你可以点击『我来翻译』按钮来参与翻译。


A primary expression of the form

a[x]

denotes the element of the array, pointer to array, slice, string or map a indexed by x. The value x is called the index or map key, respectively. The following rules apply:

If a is not a map:

  • the index x must be of integer type or an untyped constant
  • a constant index must be non-negative and representable by a value of type int
  • a constant index that is untyped is given type int
  • the index x is in range if 0 <= x < len(a), otherwise it is out of range

For a of array type A:

  • constant index must be in range
  • if x is out of range at run time, a run-time panic occurs
  • a[x] is the array element at index x and the type of a[x] is the element type of A

For a of pointer to array type:

  • a[x] is shorthand for (*a)[x]

For a of slice type S:

  • if x is out of range at run time, a run-time panic occurs
  • a[x] is the slice element at index x and the type of a[x] is the element type of S

For a of string type:

  • constant index must be in range if the string a is also constant
  • if x is out of range at run time, a run-time panic occurs
  • a[x] is the non-constant byte value at index x and the type of a[x] is byte
  • a[x] may not be assigned to

For a of map type M:

  • x's type must be assignable to the key type of M
  • if the map contains an entry with key xa[x] is the map element with key x and the type of a[x] is the element type of M
  • if the map is nil or does not contain such an entry, a[x] is the zero value for the element type of M

Otherwise a[x] is illegal.

An index expression on a map a of type map[K]V used in an assignment or initialization of the special form

v, ok = a[x]
v, ok := a[x]
var v, ok = a[x]

yields an additional untyped boolean value. The value of ok is true if the key x is present in the map, and false otherwise.

Assigning to an element of a nil map causes a run-time panic.

本文章首发在 LearnKu.com 网站上。

本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。

讨论数量: 0
发起讨论 只看当前版本


暂无话题~