Skip to the workspace
Pebellslearn by building
Arrays & Slices  ›  Lesson

Arrays

Arrays 12 minA Go array has a fixed length that is part of its type, and it is a value: assigning or passing an array copies every element.

golang / Arrays

Explore each scene at your own pace.

01 · The rule

The rule

Arrays

A Go array has a fixed length that is part of its type, and it is a value: assigning or passing an array copies every element.

Inspect fixed length, element types and value copying in array assignments.

tally wants to show a podium: the three most common words, always exactly three. When the size of a collection is part of what it means, Go's array is the right shape. Arrays are also the hidden storage beneath every slice, so understanding them first makes the next lessons easy.

The rule

An array's length is part of its type, and arrays copy as values.

var top [3]string              // ["" "" ""], zero values
top[0] = "the"

podium := [3]string{"the", "cat", "sat"}
counts := [...]int{9, 4, 2}    // [...] counts for you: [3]int
fmt.Println(len(podium))       // 3, fixed forever

Length is part of the type. [3]string and [4]string are different types. You cannot assign one to the other, and a function that takes [3]string will not accept a [4]string. The length must be a constant known at compile time.

Arrays are values. Assigning or passing an array copies all of its elements:

a := [3]int{1, 2, 3}
b := a        // full copy
b[0] = 100
fmt.Println(a[0]) // 1

The same happens with function arguments: the function gets its own copy, so changes inside do not reach the caller. For big arrays that copy also costs time.

Other properties that follow from being a value:

  • Arrays of comparable elements can be compared with ==: [2]int{1, 2} == [2]int{1, 2} is true.
  • An index known at compile time is checked by the compiler: top[5] on a [3]string does not build. A variable index out of range panics at run time.

In practice, most Go code uses slices, which are views onto arrays. Arrays suit fixed shapes: a 3-word podium, an RGB colour [3]uint8, a SHA-256 hash [32]byte.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.