Arrays
An array is a numbered sequence of elements whose length is part of the type. [3]int and [4]int are different types. Assignment copies every element.
Detailed Explanation
var ids [3]int is three integers in a row, already zeroed. The length 3 is in the type. You cannot pass a [3]int to a function that wants [4]int. You cannot grow an array. That rigidity is why most Go code uses slices. Arrays still matter as the storage slices sit on, as a fixed-size value you can copy, and as a compile-time size guarantee.
Length is a type. [2]byte is a reasonable key for a pair of flags. [32]byte is a SHA-256 digest you can compare with == and use as a map key. A slice of 32 bytes cannot do either without a conversion.
Values, not references. b := a copies all elements. Passing an array to a function copies it. For anything larger than a handful of words, pass a pointer (*[32]byte) or a slice (digest[:]). The slice form is the usual API: callers pass any backing storage, and the length is not frozen in the type.
Literals. [3]int{1, 2, 3} sets all elements. [3]int{1} sets the first and zeros the rest. [...]int{1, 2, 3} lets the compiler count. Indexed literals [...]int{1: 9} produce a two-element array with a zero at index 0.
Arrays are comparable when the element type is. [2]int{1, 2} == [2]int{1, 2} is true. [2][]int is not comparable. This is one of the few reasons to keep an array instead of a slice: a hash, a small coordinate, an IPv4 address as [4]byte.
What it costs. An array lives where you put it: on the stack as a local, inside a struct, or on the heap if it escapes. There is no header. A [1 << 20]byte local is a megabyte on the stack and can blow a small goroutine stack (which then grows). Prefer make([]byte, n) for large or runtime sizes.
Code Examples
package main
import "fmt"
func main() {
var ids [3]int
ids[0] = 10
fmt.Println(len(ids), ids[1]) // 3 0
digest := [2]byte{0xab, 0xcd}
copyOf := digest // independent copy
copyOf[0] = 0
fmt.Println(digest[0]) // 171
}func asSlice(a [32]byte) []byte {
return a[:] // returning this escapes a to the heap
}func compare() {
a := [2]int{1, 2}
fmt.Println(a == [2]int{1, 2})
}Common Gotchas
`[3]int` and `[4]int` are not assignable to each other
convert through a slice or copy element-wise.
Passing an array copies it
a function that fills `func load(buf [1024]byte)` does not fill the caller's array. Use `[]byte` or `*[1024]byte`.
`len` of an array is a constant
`len(ids)` on a `[3]int` is `3` even if you never wrote to it. There is no "used length" separate from capacity — that is a slice.
Most APIs should take slices
keep arrays for fixed-size values you want to copy or compare.