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 valuex
is called the index or map key, respectively. The following rules apply:If
a
is neither a map nor a type parameter:
Alright, so we’re looking at the rules that apply to any of the following types: array, pointer to array, slice, or string—except for type parameters of these types, which have special rules we’ll get to.
var i = int(3) // valid
var j = int8(4) // valid
const k = 12 // valid
const l = -7 // not valid, although it does conform to the first rule
const m = "chicken" // not valid, although it does conform to the first rule
- a constant index must be non-negative and representable by a value of type
int
This is the rule that makes -7
and "chicken"
above invalid.
- a constant index that is untyped is given type
int
So if we’re using the untyped constant k
from above, it’s treated as if it were int(k)
.
- the index
x
is in range if0 <= x < len(a)
, otherwise it is out of range
Given this rule:
s := []string{"foo","bar","baz","qux"}
s[i] // valid; i's value of 3 is in range
s[j] // invalid; j's value of 4 is out of range
Quotes from The Go Programming Language Specification Version of August 2, 2023