Arrays and fixed-size buffers

An array is a numbered sequence of values of one type, and its length is part of its type: [3]int and [4]int are different types that cannot be assigned to each other. The length is fixed when the program is compiled, so an array is the right container for a buffer whose size the program knows, and the wrong one for a growing list, which is what slices are for.

Declaring an array

A declared array is full of zero values, not of garbage. A composite literal fills it, an index in the literal sets one element and leaves the rest zeroed, and the three dots let the compiler count the elements of the literal without repeating the number.

package main import "fmt" func main() { var zero [3]int fmt.Println("zero:", zero) primes := [5]int{2, 3, 5, 7, 11} fmt.Println("primes:", primes, len(primes)) sparse := [...]string{0: "a", 3: "d"} fmt.Println("sparse:", sparse, len(sparse)) total := 0 for i, v := range primes { fmt.Printf("index %d holds %d\n", i, v) total += v } fmt.Println("total:", total) primes[0] = 1 fmt.Println("after the write:", primes[0]) }

go run arrays.go

zero: [0 0 0]
primes: [2 3 5 7 11] 5
sparse: [a d] 4
index 0 holds 2
index 1 holds 3
index 2 holds 5
index 3 holds 7
index 4 holds 11
total: 28
after the write: 1

len is a compile-time constant for an array, so a loop bound from it costs nothing. The index in range and in primes[i] is checked at run time: an index outside the length panics with index out of range [5] with length 5 instead of reading memory next to the array, which is the safety a C array does not have.

An array is a value

Assignment copies every element. b := a gives b its own storage, so writing to b[0] leaves a alone. Because the elements are values, two arrays of a comparable element type can be compared with ==, which compares every element in turn.

package main import "fmt" func main() { a := [3]int{1, 2, 3} b := a b[0] = 100 fmt.Println("a:", a) fmt.Println("b:", b) fmt.Println("a == b:", a == b) fmt.Println("a == [3]int{1, 2, 3}:", a == [3]int{1, 2, 3}) }

go run copy.go

a: [1 2 3]
b: [100 2 3]
a == b: false
a == [3]int{1, 2, 3}: true

The copy is what makes an array unlike a slice: a slice assignment copies three words that describe the same storage, while an array assignment copies all the data. For a large array that is expensive, and the next section shows the pointer that avoids it. An array with an element type that cannot be compared, such as a slice, cannot be compared either, and == on it is a compiler error.

Passing an array to a function

A function argument is passed by value too, so a function that takes [4]byte edits a copy. To let it change the caller's buffer, pass the address: *[4]byte is a pointer to the whole array, and range and indexing work through it without an explicit star.

package main import "fmt" func clearByValue(buf [4]byte) { buf[0] = 0 } func clearByPointer(buf *[4]byte) { buf[0] = 0 } func sum(buf *[4]byte) int { total := 0 for _, b := range buf { total += int(b) } return total } func main() { buf := [4]byte{1, 2, 3, 4} fmt.Println("sum:", sum(&buf)) clearByValue(buf) fmt.Println("after the value call:", buf) clearByPointer(&buf) fmt.Println("after the pointer call:", buf) }

go run pass.go

sum: 10
after the value call: [1 2 3 4]
after the pointer call: [0 2 3 4]

The first call changed nothing outside itself; the second changed the first byte for good. This is the same choice between a value and a pointer that the pointers lesson made for a struct, and real Go code passes a slice where this lesson passes a pointer to an array, because a slice already describes shared storage.

Arrays of arrays

An element may itself be an array, which gives a rectangular grid with a fixed shape. The outer length and the length of a row are separate numbers, and grid[1][2] reaches one cell.

package main import "fmt" func main() { grid := [2][3]int{ {1, 2, 3}, {4, 5, 6}, } fmt.Println("rows:", len(grid), "columns:", len(grid[0])) for r, row := range grid { for c, v := range row { fmt.Printf("(%d,%d)=%d ", r, c, v) } fmt.Println() } grid[1][2] = 60 fmt.Println(grid) }

go run grid.go

rows: 2 columns: 3
(0,0)=1 (0,1)=2 (0,2)=3
(1,0)=4 (1,1)=5 (1,2)=6
[[1 2 3] [4 5 60]]

The grid is one contiguous block of 2 * 3 * 8 bytes, so walking it row by row is cache friendly. A grid of slices is the ragged alternative, and a [][]int is not a two-dimensional array: it is a slice of descriptors that point at separate rows. The maps lesson follows the other branch, a container indexed by a key rather than by a number.

The size cannot be ignored

Since the length belongs to the type, a literal of the wrong length does not fit the variable, and the compiler says so before the program runs.

package main import "fmt" func main() { var buf [3]int = [4]int{1, 2, 3, 4} fmt.Println(buf) }

go build -o badsize badsize.go 2>&1 | head -3

# command-line-arguments
./badsize.go:6:19: cannot use [4]int{…} (value of type [4]int) as [3]int value in variable declaration

The fix is to let the variable and the literal agree, usually by declaring buf := [4]int{1, 2, 3, 4} or [...]int{1, 2, 3, 4}. The types lesson explains why a named array type is a third, distinct type again.

Exercises

  1. Declare var counts [26]int and count the letters of a lowercase word in it. Why does this need no map?
  2. Reverse an array in place with two indices that move towards each other. How many swaps does a five-element array need?
  3. Write func max(a [5]int) (int, int) that returns the largest value and its index, then a second version that takes *[5]int. Which one copies the data?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is the type of [3]int in the declaration var a [3]int?

    Answer

    An array of three ints

    The bracket with a length is an array type; a bracket without one is a slice.

  2. What does var a [3]int contain before anything is assigned?

    Answer

    Three zero values

    An array is a value, and every element starts at the zero value of its element type.

  3. What is the length of [...]string{0: "a", 3: "d"}?

    Answer

    4

    The highest index is 3, so the compiler counts four elements and the two that are not named are empty strings.

  4. Is the length part of an array's type?

    Answer

    Yes, [3]int and [4]int are different types

    The length is in the type, which is why an array of the wrong length cannot be assigned.

  5. What does this program print? package main import "fmt" func main() { a := [3]int{1, 2, 3} b := a b[0] = 100 fmt.Println(a[0], b[0]) }

    Answer

    1 100

    Assignment copies the whole array, so the write reaches only b.

  6. What does this program print? package main import "fmt" func main() { a := [3]int{1, 2, 3} b := a b[0] = 100 fmt.Println("a:", a) fmt.Println("b:", b) }

    Answer

    a: [1 2 3] / b: [100 2 3]

    The two arrays print on separate lines and hold different first elements.

  7. Can two arrays be compared with ==?

    Answer

    Yes, when their element type is comparable

    == compares the elements one by one; an element type such as a slice makes the array uncomparable.

  8. How is an array passed to a function?

    Answer

    By value: the function receives a copy

    Every argument is a copy, so a function that must change the array takes a pointer to it.

  9. What does this program print? package main import "fmt" func main() { grid := [2][3]int{{1, 2, 3}, {4, 5, 6}} fmt.Println(len(grid), len(grid[0])) }

    Answer

    2 3

    The first number is the number of rows, the second the number of columns.

  10. What happens at a[5] when a is a [5]int?

    Answer

    A run-time panic: index out of range

    The compiler knows the length and the runtime inserts a bounds check on every index.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image