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
xmust be of integer type or untyped; it is in range if0 <= x < len(a), otherwise it is out of range - a constant index must be non-negative and representable by a value of type
int
For a of array type A:
- a constant index must be in range
- if
xis out of range at run time, a run-time panic occurs a[x]is the array element at indexxand 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
xis out of range at run time, a run-time panic occurs a[x]is the slice element at indexxand the type ofa[x]is the element type ofS
For a of string type:
- a constant index must be in range if the string
ais also constant - if
xis out of range at run time, a run-time panic occurs a[x]is the non-constant byte value at indexxand the type ofa[x]isbytea[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 value with keyxand the type ofa[x]is the value type ofM - if the map is
nilor does not contain such an entry,a[x]is the zero value for the value 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.