Arrays in Go
| Fixed length | |
| Read and write by index | |
| Loop without len bugs | |
| When arrays are right |
Fixed length
An array holds a fixed number of elements of one type, and the length is part of the type itself: [3]int and [4]int are different types. Declare one with var to get zero values, or with a literal to set the content at once.
package main
import "fmt"
func main() {
var scores [3]int
fmt.Println(scores)
nums := [4]int{1, 2, 3, 4}
fmt.Println(nums, len(nums))
}
go run main.go
[0 0 0]
[1 2 3 4] 4
A fresh array is never empty garbage: every element starts at the zero value of its type. The size in brackets is a constant, so it cannot come from a variable.
Read and write by index
Elements are numbered from zero, so a three element array uses indexes 0, 1, and 2. Read an element with a[i] and store a new one with a[i] followed by an assignment.
package main
import "fmt"
func main() {
colors := [3]string{"red", "green", "blue"}
colors[1] = "yellow"
fmt.Println(colors[0], colors[1], colors[2])
}
red yellow blue
Going outside the valid range stops the program with a panic, which is the Go way of refusing to guess. That strictness turns off by one mistakes into loud failures instead of silent corruption.
Loop without len bugs
The classic indexing bug is walking past the last element. Loop with i starting at 0 while i stays below the result of len, and the bound always matches the array even after edits.
package main
import "fmt"
func main() {
nums := [5]int{1, 2, 3, 4, 5}
total := 0
for i := 0; i < len(nums); i++ {
total += nums[i]
}
fmt.Println(total)
}
15
Prefer len over a hardcoded number: if the literal grows from five elements to six, the loop follows automatically. Range loops from the previous lesson remove the index math completely.
When arrays are right
Arrays are values: assigning one variable to another copies every element. That makes small fixed size collections safe to pass around, for example coordinates, color triples, or a week of totals.
package main
import "fmt"
func main() {
a := [2]int{1, 2}
b := a
b[0] = 9
fmt.Println(a, b)
}
[1 2] [9 2]
For anything that grows, slices from the next lesson are the better tool. Reach for an array when the size is known up front and never changes.
Next: Slices
Article author: Arthur Isaev