Skip to content

Go Arrays

In Go, an array is a numbered sequence of elements of a single type with a fixed length.

1. Basic Usage

The size of the array is part of its type. [5]int and [10]int are distinct, incompatible types.

package main
import "fmt"

func main() {
    // 1. Declare an array of 5 integers
    var a [5]int
    fmt.Println("emp:", a) // [0 0 0 0 0] (initialized to zero value)

    // 2. Set a value at an index
    a[4] = 100
    fmt.Println("set:", a)
    fmt.Println("get:", a[4])

    // 3. Get the length
    fmt.Println("len:", len(a))

    // 4. Declare and initialize in one line
    b := [5]int{1, 2, 3, 4, 5}
    fmt.Println("dcl:", b)
}

2. Multi-Dimensional Arrays

You can compose types to build multi-dimensional data structures.

1
2
3
4
5
6
7
var twoD [2][3]int
for i := 0; i < 2; i++ {
    for j := 0; j < 3; j++ {
        twoD[i][j] = i + j
    }
}
fmt.Println("2d: ", twoD)

3. Iterating with Range

Use range to iterate over an array. If you don't need the index, use the blank identifier (_).

nums := [3]int{10, 20, 30}

// i is the index, v is the value
for i, v := range nums {
    fmt.Printf("index %d has value %d\n", i, v)
}

// Ignore the index using _
sum := 0
for _, v := range nums {
    sum += v
}

Important Notes

  1. Value Type: Arrays in Go are value types. If you assign an array to a new variable, or pass it to a function, the entire array is copied.
  2. Fixed Size: You cannot resize an array. If you need a dynamic list, use Slices instead (which are much more common in Go).