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 if0 <= x < len(a)
, otherwise it is out of range
For a
of array type A
:
- 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 indexx
and the type ofa[x]
is the element type ofA
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 indexx
and the type ofa[x]
is the element type ofS
For a
of string type:
- a 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 indexx
and the type ofa[x]
isbyte
a[x]
may not be assigned to
For a
of map type M
:
x
's type must be assignable to the key type ofM
- if the map contains an entry with key
x
,a[x]
is the map element with keyx
and the type ofa[x]
is the element type ofM
- if the map is
nil
or does not contain such an entry,a[x]
is the zero value for the element type ofM
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.
本文中的所有译文仅用于学习和交流目的,转载请务必注明文章译者、出处、和本文链接
我们的翻译工作遵照 CC 协议,如果我们的工作有侵犯到您的权益,请及时联系我们。