Learn Go← Dashboard

Fixed-size arrays and the workhorse slice type.

Arrays

An array in Go is a fixed-size sequence of elements of one type. The size is part of the type — [3]int and [4]int are different types, and you cannot use one where the other is expected.

You'll use arrays much less than slices. They're the foundation slices are built on.

Declaring

go playground
Loading...

[...] is a small convenience: you write the elements and the compiler figures out the length.

Arrays are values, not references

When you assign or pass an array, the whole thing is copied:

go playground
Loading...

That's a key difference from C and from Go slices. It's also why we usually prefer slices in practice.

Multidimensional arrays

var grid [3][3]int
grid[1][2] = 5

A [3][3]int is "an array of 3 arrays of 3 ints" — Go has no built-in matrix type, but the syntax is straightforward.

Arrays are comparable

Unlike slices, arrays of the same type can be compared with == and used as map keys:

a := [3]int{1, 2, 3}
b := [3]int{1, 2, 3}
fmt.Println(a == b) // true

m := map[[2]string]int{}    // key is a [2]string array
m[[2]string{"go", "lang"}] = 1
Are `[3]int` and `[4]int` the same type?