Go by Example

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, so assignment or a value parameter copies every element. A [10000]byte value contains 10 KB; use a slice when callers need a variable-length sequence. Arrays still fit fixed-size values such as a [32]byte digest. Go decides where values are stored, so code should not rely on stack placement.

Enjoyed this? Get more software craft delivered to your inbox.