Clear, practical technology insights BSOD Code Lookup · Windows Error Code Lookup · Wi-Fi Troubleshooting · PC Troubleshooting Checklist

Arrays in Go: Declaration, Indexing, and Iteration

Declare and initialize fixed-length arrays in Go, loop through their elements, create nested arrays, and decide when to use a slice.

Table of Contents

A Go array stores a fixed number of elements of one type. For example, [3]int holds three integers. Its length is part of the type, so [3]int and [4]int are different types. Use a slice such as []int when the number of items can change.

3 Best Windows Sandbox Alternatives for Windows 11 Home Picture 1

Declare and initialize an array

Use var to declare an array with zero-valued elements, or use a literal to set the initial values. Within a function, you can use := for a short declaration. In an array literal, [...] tells Go to infer the length.

var scores [3]int                  // [0 0 0]
scores[0] = 85
fixed := [3]int{85, 92, 78}         // [85 92 78]
inferred := [...]string{"red", "blue"} // [2]string
fmt.Println(len(fixed), len(inferred)) // 3 2

Omitted elements take the zero value for their type. For example, [3]string{"red"} contains "red" followed by two empty strings.

3 Best Windows Sandbox Alternatives for Windows 11 Home Picture 2

Read, change, and loop through elements

Indexes start at zero. For an array with three elements, the valid indexes are 0, 1, and 2. An out-of-range constant index fails to compile. An out-of-range index evaluated at runtime causes a panic.

package main

import "fmt"

func main() {
    scores := [3]int{85, 92, 78}
    scores[1] = 94

    for index, score := range scores {
        fmt.Printf("%d: %dn", index, score)
    }
}

The loop prints 0: 85, 1: 94, and 2: 78 on separate lines. Use _ in place of the index if you only need the element.

3 Best Windows Sandbox Alternatives for Windows 11 Home Picture 3

Make an array of arrays

A type such as [2][3]int represents two rows of three integers. Access an element as grid[row][column]:

grid := [2][3]int{
    {1, 2, 3},
    {4, 5, 6},
}
fmt.Println(grid[1][2]) // 6

Know when Go copies an array

Assigning one array to another variable copies its elements. Passing an array as a function argument also copies it. Slicing an addressable array with scores[:] creates a slice that initially shares its elements, so changes through that slice are visible in the array. See Effective Go’s explanation of arrays and slices.

Discussion

Reader Comments 0

Sign in with email or Google to join the discussion.