These are the notes for Go episode 12. Until now every variable held exactly one value. Real data comes in groups: a week of sales, a class of marks, a hall of seats. Today you meet Go's first collection (a value that holds many values): the array. You will learn array types, indexes and elements, len, out-of-bounds errors (compile time and run time), why the length is part of the type, array literals, [...] length inference, indexed literals, value semantics (arrays are copied), passing arrays to functions, comparing arrays with ==, and multi-dimensional arrays. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24).
The problem: seven variables for one week
Raju runs a chai stall and writes down the cups he sells each day. Seven days, seven variables:
package main
import "fmt"
func main() {
mon, tue, wed, thu := 120, 95, 140, 80
fri, sat, sun := 110, 150, 200
fmt.Println("week:", mon+tue+wed+thu+fri+sat+sun)
total := 0
for i := 0; i < 7; i++ {
total += day[i]
}
}
# command-line-arguments
./main.go:13:18: undefined: day
The long sum works for a week, but a month needs 30 variables and a year 365. And a loop can't help: mon, tue... are seven unrelated names, and a loop can only step through numbers. We need one name for the whole week, and a number to pick each day.
Your first array
Think of a weekly pill box:
| A weekly pill box | In Go | Name |
|---|---|---|
| One box for the whole week | sales |
one variable |
| Exactly seven compartments, same kind of thing | [7]int |
an array type: length 7, element type int |
| Open compartment number 3 | sales[3] |
an index picks one element |
- An array is a numbered sequence of a fixed number of values, all of the same type.
- Each value inside is an element.
- You pick an element by its index (position) in square brackets. Indexes start at 0: the first element is
sales[0], the seventh issales[6]. len(a)is a built-in function that returns the number of elements (the length).
package main
import "fmt"
func main() {
var sales [7]int
fmt.Println(sales, len(sales))
sales[0] = 120
sales[6] = 200
fmt.Println(sales)
fmt.Println("Sunday:", sales[6])
}
[0 0 0 0 0 0 0] 7
[120 0 0 0 0 0 200]
Sunday: 200
A new array starts with every element at its zero value (0 for int, "" for string, false for bool).
Every element type has its own zero value:
package main
import "fmt"
func main() {
var names [3]string
var open [3]bool
var prices [3]float64
fmt.Printf("%q %v %v\n", names, open, prices)
}
["" "" ""] [false false false] [0 0 0]
%q prints strings with their quotes, so the empty strings are visible. A Go array is never full of leftover garbage: it always starts clean.
Looping over an array
An array literal writes the type and then the values in braces:
package main
import "fmt"
func main() {
sales := [7]int{120, 95, 140, 80, 110, 150, 200}
total, best := 0, 0
for i := 0; i < len(sales); i++ {
total += sales[i]
if sales[i] > sales[best] {
best = i
}
}
fmt.Println("week:", total)
fmt.Println("best day:", best, sales[best])
}
week: 895
best day: 6 200
i < len(sales) keeps the loop inside the array whatever its size. For a year, only the type changes: [365]int.
Index out of range
Valid indexes are 0 to len - 1. A constant index outside that range is caught by the compiler:
package main
import "fmt"
func main() {
sales := [7]int{120, 95, 140, 80, 110, 150, 200}
fmt.Println(sales[7])
}
# command-line-arguments
./main.go:7:23: invalid argument: index 7 out of bounds [0:7]
[0:7] means "from 0 up to, but not including, 7". If the index is a variable, the compiler can't always know its value, so Go checks while the program runs:
package main
import "fmt"
func main() {
sales := [7]int{120, 95, 140, 80, 110, 150, 200}
day := 7
fmt.Println(sales[day])
}
panic: runtime error: index out of range [7] with length 7
goroutine 1 [running]:
main.main()
/tmp/main.go:8 +0x15
exit status 2
This run-time check of every index is called bounds checking. Instead of silently reading memory that isn't part of the array (which C allows), Go stops with a panic.
The off-by-one mistake
The most common way to hit this panic is a loop condition with <=:
package main
import "fmt"
func main() {
sales := [7]int{120, 95, 140, 80, 110, 150, 200}
total := 0
for i := 0; i <= len(sales); i++ {
total += sales[i]
}
fmt.Println(total)
}
panic: runtime error: index out of range [7] with length 7
goroutine 1 [running]:
main.main()
/tmp/main.go:9 +0xbe
exit status 2
With <=, the loop tries i = 7, one past the end. An off-by-one error is a loop that runs one time too many or too few. The condition must be i < len(sales).
range over an array
Let Go do the counting: range walks an array from the first element to the last, giving you the index and the value on each pass.
package main
import "fmt"
func main() {
sales := [7]int{120, 95, 140, 80, 110, 150, 200}
total := 0
for _, cups := range sales {
total += cups
}
fmt.Println("week:", total)
for i, cups := range sales {
if cups >= 150 {
fmt.Println("busy day", i, cups)
}
}
}
week: 895
busy day 5 150
busy day 6 200
for i, v := range a:iis the index,va copy of the element.- Use
_(the blank identifier) for the part you don't need:for _, cups := range sales. for i := range agives only the index.rangeis used constantly with slices (episode 13).
The length is part of the type
package main
import "fmt"
func main() {
var week [7]int
var school [5]int
fmt.Printf("%T and %T\n", week, school)
week = school
}
# command-line-arguments
./main.go:9:12: cannot use school (variable of type [5]int) as [7]int value in assignment
A 6-egg tray and a 12-egg tray are different products. In Go, [5]int and [7]int are different types. That's why an array can never grow or shrink, and why a function written for [7]int can't take a [5]int. The length must be a constant known when the program is compiled.
Array literals
package main
import "fmt"
func main() {
days := [...]string{"Mon", "Tue", "Wed",
"Thu", "Fri", "Sat", "Sun"}
fmt.Println(len(days), days[0], days[6])
holiday := [7]bool{6: true}
fmt.Println(holiday)
stock := [...]int{2: 50, 4: 10}
fmt.Println(stock, len(stock))
}
7 Mon Sun
[false false false false false false true]
[0 0 50 0 10] 5
| Form | Meaning |
|---|---|
[7]int{120, 95, ...} |
length 7; missing values at the end are zero |
[...]string{"Mon", ...} |
length inference: Go counts the values |
[7]bool{6: true} |
indexed literal: set only index 6, the rest are zero |
[...]int{2: 50, 4: 10} |
both: the highest index is 4, so the length is 5 |
A literal written across several lines needs a comma or the closing brace at the end of each line, because of Go's semicolon insertion (episode 1).
Arrays are values: they get copied
package main
import "fmt"
func main() {
sales := [7]int{120, 95, 140, 80, 110, 150, 200}
backup := sales
backup[0] = 0
fmt.Println("sales: ", sales)
fmt.Println("backup:", backup)
}
sales: [120 95 140 80 110 150 200]
backup: [0 95 140 80 110 150 200]
Assigning an array copies every element: an array is a value, like an int (value semantics, episode 11). The same happens when you pass an array to a function:
package main
import "fmt"
func resetWeek(w [7]int) {
for i := 0; i < len(w); i++ {
w[i] = 0
}
}
func main() {
sales := [7]int{120, 95, 140, 80, 110, 150, 200}
resetWeek(sales)
fmt.Println(sales)
}
[120 95 140 80 110 150 200]
The function reset its own copy. Pass a pointer to the array instead:
package main
import "fmt"
func resetWeek(w *[7]int) {
for i := 0; i < len(w); i++ {
w[i] = 0
}
}
func main() {
sales := [7]int{120, 95, 140, 80, 110, 150, 200}
resetWeek(&sales)
fmt.Println(sales)
}
[0 0 0 0 0 0 0]
With a pointer to an array, w[i] and len(w) work directly (Go dereferences for you). Copying 7 ints is cheap, but an array of a million elements would be copied on every call: one reason Go programmers mostly use slices (next episode).
Comparing arrays
Because arrays are values, == and != work when the element type is comparable. Two arrays are equal when they have the same type and every element matches, in order:
package main
import "fmt"
func main() {
key := [5]string{"A", "C", "B", "D", "A"}
asha := [5]string{"A", "C", "B", "D", "A"}
ravi := [5]string{"A", "C", "D", "D", "A"}
fmt.Println("Asha full marks:", asha == key)
fmt.Println("Ravi full marks:", ravi == key)
}
Asha full marks: true
Ravi full marks: false
Comparing arrays of different lengths doesn't compile:
package main
import "fmt"
func main() {
key := [5]string{"A", "C", "B", "D", "A"}
short := [4]string{"A", "C", "B", "D"}
fmt.Println(short == key)
}
# command-line-arguments
./main.go:8:26: invalid operation: short == key (mismatched types [4]string and [5]string)
Multi-dimensional arrays
A cinema hall has 3 rows (A, B, C) of 5 seats. That's an array of rows, where each row is an array of seats: [3][5]bool. An array of arrays is a multi-dimensional array; this one is two-dimensional, a grid. A seat needs two indexes: seats[row][seat]. Row B, seat 3 is seats[1][2].
package main
import "fmt"
func main() {
var seats [3][5]bool
seats[1][2] = true
fmt.Println(seats[0])
fmt.Println(seats[1])
fmt.Println(seats[2])
fmt.Println(len(seats), len(seats[0]))
}
[false false false false false]
[false false true false false]
[false false false false false]
3 5
len(seats) is the number of rows; len(seats[0]) the number of seats in a row.
Mini project: a cinema seat map
package main
import "fmt"
func main() {
var hall [3][5]bool
hall[0][1], hall[0][2], hall[2][4] = true, true, true
for r := 0; r < len(hall); r++ {
fmt.Print(string(rune('A'+r)), " ")
for c := 0; c < len(hall[r]); c++ {
mark := ". "
if hall[r][c] {
mark = "X "
}
fmt.Print(mark)
}
fmt.Println()
}
}
A . X X . .
B . . . . .
C . . . . X
Extension 1, count the free seats:
package main
import "fmt"
func main() {
var hall [3][5]bool
hall[0][1], hall[0][2] = true, true
hall[2][4] = true
free := 0
for r := 0; r < len(hall); r++ {
fmt.Print(string(rune('A'+r)), " ")
for c := 0; c < len(hall[r]); c++ {
if hall[r][c] {
fmt.Print("X ")
} else {
fmt.Print(". ")
free++
}
}
fmt.Println()
}
fmt.Println("free seats:", free)
}
A . X X . .
B . . . . .
C . . . . X
free seats: 12
- A nested loop (a loop inside a loop) walks a grid: the outer loop over rows, the inner loop over the seats of that row.
'A'+ris a rune (a character code, episode 4) for A, B, C;string(rune(...))turns it into text.
Extension 2: write book(hall *[3][5]bool, r, c int) bool that refuses a seat that's already taken or out of range.
The next problem: the cinema adds a fourth row, or Raju wants to keep adding days. An array's size is fixed in its type. We need a list that can grow: slices.
Common mistakes (and the real error messages)
| You wrote | Real error / what happens | Fix |
|---|---|---|
sales[7] on a [7]int |
invalid argument: index 7 out of bounds [0:7] |
last index is len-1: sales[6] |
day := 7; sales[day] |
panic: runtime error: index out of range [7] with length 7 |
check day < len(sales) |
for i := 0; i <= len(a); i++ |
panic: runtime error: index out of range on the last pass |
i < len(a) |
week = school ([7]int = [5]int) |
cannot use school (variable of type [5]int) as [7]int value in assignment |
lengths must match |
short == key with different lengths |
invalid operation: short == key (mismatched types [4]string and [5]string) |
compare same types |
resetWeek(sales) expecting a change |
no error: the copy changes | resetWeek(&sales) with *[7]int |
n := 7; var a [n]int |
invalid array length n |
the length must be a constant |
Practice
- Print the average and the worst day of a
[7]intof sales. - Reverse a
[5]intin place (swap first and last, and so on). - Given an answer key and three students' sheets, count full marks.
- Make a tic-tac-toe board
[3][3]runeand print it as a grid.
Solutions
- Convert to
float64for the average (episode 4):
package main
import "fmt"
func main() {
sales := [7]int{120, 95, 140, 80, 110, 150, 200}
total, worst := 0, 0
for i := 0; i < len(sales); i++ {
total += sales[i]
if sales[i] < sales[worst] {
worst = i
}
}
fmt.Printf("average %.1f, worst day %d (%d cups)\n", float64(total)/float64(len(sales)), worst, sales[worst])
}
average 127.9, worst day 3 (80 cups)
- Two indexes walking towards each other:
package main
import "fmt"
func main() {
a := [5]int{1, 2, 3, 4, 5}
for i, j := 0, len(a)-1; i < j; i, j = i+1, j-1 {
a[i], a[j] = a[j], a[i]
}
fmt.Println(a)
}
[5 4 3 2 1]
3.
package main
import "fmt"
func main() {
key := [3]string{"A", "C", "B"}
sheets := [3][3]string{{"A", "C", "B"}, {"A", "B", "B"}, {"A", "C", "B"}}
full := 0
for i := 0; i < len(sheets); i++ {
if sheets[i] == key {
full++
}
}
fmt.Println("full marks:", full)
}
full marks: 2
4.
package main
import "fmt"
func main() {
board := [3][3]rune{{'X', 'O', 'X'}, {'.', 'X', 'O'}, {'O', '.', 'X'}}
for r := 0; r < 3; r++ {
for c := 0; c < 3; c++ {
fmt.Print(string(board[r][c]), " ")
}
fmt.Println()
}
}
X O X
. X O
O . X
Quick quiz
What does this print?
func main() {
a := [3]int{1, 2, 3}
b := a
b[0] = 9
fmt.Println(a[0], b[0], len(b))
}
- A.
9 9 3 - B.
1 9 3 - C.
1 9 2 - D. compile error
Answer
B. 1 9 3. b := a copies the whole array, so changing b[0] leaves a untouched. The length is still 3.
Interview questions
- What is an array in Go? Can its length change?
- Why are
[5]intand[7]intdifferent types? - What's the difference between
invalid argument: index ... out of boundsandpanic: runtime error: index out of range? - What does
[...]mean in an array literal? What is an indexed literal? - What happens when you assign an array to another variable, or pass it to a function?
- How do you let a function modify an array?
- Can you compare two arrays with
==? When? - How do you declare and loop over a 2D array?
- Why do Go programmers use slices more than arrays?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Collection | a value that holds many values | an array, a slice, a map |
| Array | a fixed number of values of one type, under one name | [7]int |
| Element | one value inside an array | sales[2] is 140 |
| Index | an element's position, starting from 0 | 0 to 6 in a [7]int |
| Indexing | picking an element with [ ] |
sales[6] |
| Array type | [length]elementType |
[7]int, [3][5]bool |
| Element type | the type of every element | int in [7]int |
| Length | the number of elements; part of the type | 7 |
| len | built-in function returning the length | len(sales) |
| Zero value | the starting value of an element | 0, "", false |
| Array literal | an array written in code | [7]int{120, 95, ...} |
[...] length inference |
Go counts the literal's values | [...]string{"Mon", "Tue"} |
| Indexed literal | a literal that sets chosen indexes | [7]bool{6: true} |
| Out of bounds | an index outside 0 to len−1 | sales[7] |
| Bounds checking | Go checking every index at run time | the index-out-of-range panic |
| Panic | Go stopping the program because of a run-time error | index out of range [7] with length 7 |
| Value semantics | assigning or passing copies the whole value | backup := sales |
| Pointer to an array | the address of an array; avoids copying | *[7]int, &sales |
| Comparable | a type whose values can be compared with == |
arrays of ints, strings, bools |
| Multi-dimensional array | an array whose elements are arrays | [3][5]bool |
| 2D array / grid | rows and columns | the cinema hall |
| Off-by-one error | a loop that runs one time too many or too few | i <= len(a) |
| range | walks a collection, giving index and value | for i, v := range sales |
| Nested loop | a loop inside a loop | rows, then seats |
| Rune | a character code | 'A' |
| Slice | a growable view of an array (episode 13) | []int{1, 2, 3} |
Summary
- An array stores a fixed number of values of one type under one name. Reach elements by index, from 0 to
len-1. - Bad indexes are caught by the compiler when constant, and by a panic at run time otherwise (bounds checking).
- The length is part of the type:
[5]int≠[7]int, so arrays never grow. - Literals:
[7]int{...},[...]to let Go count, indexed{6: true}. - Arrays are values: copied on assignment and when passed. Pass
*[N]Tto change the original.==compares element by element. - Arrays of arrays make grids:
hall[row][seat].
Next episode: slices. A list that grows: make, append, len, cap and slicing.