Arrays
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 foreverLength 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]) // 1The 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]stringdoes 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.
The shortcut
Whenever an array moves — assignment, function call, return — picture a photocopier. The receiver gets its own sheet; scribbling on it never changes the original.
The call
reset(top)passes the array. The photocopier runs:tis a new[3]string.
Drills
Answer fast — trust the rule.
What is the type of [...]string{"a", "b", "c", "d"}?
a := [2]int{1, 2}; b := a; b[1] = 9. What is a?
Can a [4]int be passed to func sum(v [3]int) int?
What does fmt.Println([2]string{"go", "go"} == [2]string{"go", "go"}) print?
Remember
- An array's length is part of its type, and arrays copy as values.
- Shortcut: picture a photocopier every time an array is assigned or passed.
- Trap: changing an array inside a function does not change the caller's array.
