Arrays
Fixed-length typed arrays - declaration, zero initialisation, array literals, comparison, and multi-dimensional arrays.
An array in Go has a fixed length that is part of its type: [5]int and [10]int are two distinct types. Arrays are zero-initialised and comparable. In practice, slices (backed by arrays) are used far more often.
Declare an array with var - every element is initialised to the zero value of the element type. Use an array literal to initialise with specific values. The ... syntax infers the length from the literal.
package main
import "fmt"
func main() {
var zeros [5]int
fmt.Println(zeros) // [0 0 0 0 0]
primes := [5]int{2, 3, 5, 7, 11}
fmt.Println(primes) // [2 3 5 7 11]
// Infer length from literal
words := [...]string{"foo", "bar", "baz"}
fmt.Println(len(words)) // 3
}Arrays are comparable with == if their element type is comparable. Two arrays are equal when all corresponding elements are equal.
package main
import "fmt"
func main() {
a := [3]int{1, 2, 3}
b := [3]int{1, 2, 3}
c := [3]int{1, 2, 4}
fmt.Println(a == b) // true
fmt.Println(a == c) // false
}Multi-dimensional arrays are arrays of arrays. Access with consecutive index expressions.
package main
import "fmt"
func main() {
var grid [3][3]int
for i := range grid {
for j := range grid[i] {
grid[i][j] = i*3 + j
}
}
fmt.Println(grid)
// [[0 1 2] [3 4 5] [6 7 8]]
}In production
Arrays are value types in Go - assigning or passing them copies every element. Passing a [10000]byte to a function copies 10 KB on the stack; you almost always want a slice or a pointer to the array in real code. The fixed-length property makes arrays useful for fixed-size cryptographic or binary structures (e.g., [32]byte for a SHA-256 digest), where the size constraint is a feature, not a limitation.
Enjoyed this? Get more essays on software craft delivered to your inbox.
Subscribe free