I hope you can join me again today on my live stream, when I’ll be continuing my series about deploying a simple Go app to Kubernetes.
Last week we started with index expressions. Today we look at the additional rules that apply specifically to index expressions for arrays.
Index expressions
… For a of array type
A
:
- a constant index must be in range
Since the length of an array is known at compile time, it is a compilation error to use a constant index that is out of range.
var a [5]string
a[12] // index 12 out of bounds [0:5]
const i = 7
a[i] // index 7 out of bounds [0:5]
- if
x
is out of range at run time, a run-time panic occurs
When the index is determined at runtime, the compler won’t complain, but you will get a run-time panic if you try to use an out-of-bounds index:
var a [5]string
i := 7
a[i] // panic: runtime error: index out of range [7] with length 5
a[x]
is the array element at indexx
and the type ofa[x]
is the element type ofA
var a [5]string
s = a[3] // s's type is `string`, because that's the element type of a
For a of pointer to array type:
a[x]
is shorthand for(*a)[x]
As a nifty short-hand, we can reference elements of array pointers the same way we do array values:
var a = &[5]string{}
i := a[3] // These are
j := (*a)[3] // equivalent
Quotes from The Go Programming Language Specification Version of August 2, 2023