Go by Example

Arrays

Arrays hold a fixed number of values, and their length is part of their type.

An array holds a fixed number of values, and its length is part of its type. [5]int and [10]int are different types. Each element starts at its zero value, the default for its type, such as 0 for an integer. An array can be checked with == when its elements can also be compared that way.

Declare an array with var to start every element at its zero value, the default for its type. An array literal is a list of starting values in braces. Write ... to let Go count the values and choose the length.

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
}

If the element type can be compared with ==, Go can compare arrays of that type. Two arrays are equal when each value at the same position is 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

Assigning an array copies all of its elements. Use a slice, a list that can grow or shrink, when the number of values can change or when copying a large array would be wasteful. Use an array when the number of values is fixed.

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