Go Arrays

An array in Go is a fixed-size, ordered collection of elements that all share the same type.

Declaring Arrays

Arrays are declared with a length baked into their type: [5]int and [10]int are considered different types entirely, even though both hold integers. This fixed length is what separates arrays from slices, and it is checked at compile time, so you cannot accidentally resize an array or pass a [3]int where a [5]int is expected.

Declaring and Initializing Arrays

package main

import "fmt"

func main() {
	var scores [5]int
	scores[0] = 90
	scores[1] = 85

	names := [3]string{"Alice", "Bob", "Carol"}

	fmt.Println(scores)
	fmt.Println(names)
	fmt.Println("Length:", len(names))
}

Iterating Over Arrays

The range keyword is the idiomatic way to loop over an array, giving you both the index and the value on each iteration. If you only need the value, you can discard the index with the blank identifier _. Because arrays have a known, fixed length, the compiler can even bounds-check some accesses ahead of time.

Looping with range

package main

import "fmt"

func main() {
	temperatures := [4]float64{21.5, 22.0, 19.8, 23.1}

	var total float64
	for i, temp := range temperatures {
		fmt.Printf("Day %d: %.1f°C\n", i+1, temp)
		total += temp
	}

	average := total / float64(len(temperatures))
	fmt.Printf("Average: %.2f°C\n", average)
}

Arrays Are Value Types

A crucial detail: assigning an array to a new variable, or passing it to a function, copies the entire array. Modifying the copy does not affect the original. This is different from slices, which share the same underlying data. If you want a function to mutate the original array, you must pass a pointer to it explicitly.

Copy Semantics

package main

import "fmt"

func double(arr [3]int) {
	for i := range arr {
		arr[i] *= 2
	}
	fmt.Println("Inside function:", arr)
}

func main() {
	numbers := [3]int{1, 2, 3}
	double(numbers)
	fmt.Println("Original unchanged:", numbers)
}
  • Fixed length is part of the array's type, e.g. [5]int
  • Declared with var arr [n]Type or a composite literal [n]Type{...}
  • Copied by value on assignment and when passed to functions
  • Best suited for data with a known, unchanging size, like a chessboard or RGB pixel
Note: You can let the compiler count elements for you using [...]int{1, 2, 3}, which creates a [3]int automatically based on the number of items in the literal.
FeatureArraySlice
LengthFixed, part of the typeDynamic, can grow or shrink
Declaration[5]int[]int
Passed to functionsCopied entirelyShares underlying array
Common useFixed-size data (e.g. matrix row)General-purpose lists
Note: Accessing an index outside an array's bounds, like scores[10] on a [5]int, causes a runtime panic. Always check len() when the index comes from user input or a calculation.

Exercise: Go Arrays

Once a Go array is declared with a fixed size, can that size be changed later?