Arrays should not be a foreign concept to anyone who’s done programming before. But Go’s version of arrays has some peculiarities that often trip up beginners.
Array types
An array is a numbered sequence of elements of a single type, called the element type. The number of elements is called the length of the array and is never negative.
ArrayType = "[" ArrayLength "]" ElementType . ArrayLength = Expression . ElementType = Type .
The length is part of the array’s type; it must evaluate to a non-negative constant representable by a value of type
int
. The length of arraya
can be discovered using the built-in functionlen
. The elements can be addressed by integer indices 0 throughlen(a)-1
. …[32]byte [2*N] struct { x, y int32 } [1000]*float64
The most important, and often surprising, part of all of this is the sentence The length is part of the array’s type. In Go, arrays have a fixed length. They never grow or shrink. You cannot push onto, or pop off of an array. You can only change the existing elements of the array.
This does mean that the length of an array is a constant, and can thus be assigned to a const
:
var x [3]int
const y = len(x)
fmt.Println(x, y) // [0 0 0] 3
This limitation means that the array
type is often not (directly) used in Go. Instead, the more flexible slice
type, which we’ll be talking about shortly, is much more common.
Quotes from The Go Programming Language Specification, Version of January 19, 2023