Thuta Learning
Go
IntermediateProgrammingBeginner

Arrays

GoLesson 820 min

What you'll walk away with

  • Explain why [3]int and [4]int are different types
  • Create arrays with literals, with [...] and as zero values
  • Predict output when an array is assigned or passed to a function, knowing both are copies
  • Tell a bad constant index (compile error) from a bad runtime index (panic)

Explain it simply

Explain it simply

Picture an array as an egg carton. The number of slots is fixed when the carton is made, and you cannot add slots later. Every slot has a number starting at 0, so the first egg sits in slot 0.

In Go the carton's size is part of what kind of thing it is: a six-egg carton and a twelve-egg carton are different types. The other surprise is that handing the carton to someone gives them a fresh copy of the whole carton.

Problem → Why → Solution

The problem: the function changed it, but nothing changed

Programmers coming from JavaScript or Python expect a function to edit the caller's data directly when it receives an array. resetFirst() below sets the first score to 0. Yet when main() prints scores it still shows [80 90 100], and no error appears anywhere.

main.go
package main

import "fmt"

func resetFirst(s [3]int) {
	s[0] = 0 // changes the function's own copy
}

func main() {
	scores := [3]int{80, 90, 100}
	resetFirst(scores)
	fmt.Println(scores) // [80 90 100], not [0 90 100]
}

Why did nothing change?

In Go an array is a value, treated just like an int. Calling resetFirst(scores) copies all three elements into s, and the function edits only that copy. To change the caller's array you must return the edited array or pass a pointer (*[3]int).

Core concept: the length is part of the type, and arrays are values

An array type is written [N]T, where N is the number of elements and T is their type. N must be a constant and is part of the type, so [3]int and [4]int are two completely different types. Assigning a [3]int variable to a [4]int one is a compile error: "cannot use scores (variable of type [3]int) as [4]int value". The length can never change while the program runs.

There are three common ways to create one. [3]int{80, 90, 100} is a literal. [...]int{2, 3, 5} lets the compiler count the elements and fill in the length. A plain declaration like var empty [3]int gives every element its zero value: 0 for int, "" for string, false for bool. A Go array never has an "unset" slot. You can also fill chosen positions only, as in [5]string{1: "B", 3: "D"}, and the remaining slots get the zero value.

The most important point is that an array is a value. backup := scores copies every element, so changing backup never touches scores. Passing an array to a function or returning one also copies it. If the element type is comparable, two arrays can be compared element by element with ==, and an array can even be a map key.

Valid indexes run from 0 to len(a)-1. A constant index past the end, like scores[3], is caught by the compiler: "index 3 out of bounds [0:3]". When the index is a variable computed at run time, the compiler cannot know, so the program panics with "index out of range [3] with length 3" and stops.

Mental model: a fixed box that travels as a copy
  1. [N]T makes exactly N slots
  2. Every slot starts at its zero value
  3. = and calls copy the whole box
  4. Index outside 0..N-1 fails

Treat an array like a big int: every hand-off creates an independent copy.

General pattern

go
var name [N]Type                      // N zero values
name := [N]Type{v0, v1, v2}           // literal
name := [...]Type{v0, v1}             // compiler counts N
name := [N]Type{index: value}         // set chosen slots

value := name[i]                      // read, 0 <= i < N
name[i] = value                       // write
count := len(name)                    // always N

The length N is written in the type and must be a constant. [...] takes the length from the number of elements in the literal. The index: value form fills only the chosen slots and leaves the rest at their zero value.

Example: a score array and how it copies

This program builds an array of three scores, then shows indexing, len(), a zero-value array, assignment as a copy, and comparison with ==. Before you run it, predict what scores looks like after backup is changed.

main.go
package main

import "fmt"

func main() {
	scores := [3]int{80, 90, 100}
	fmt.Println(scores)
	fmt.Println("first score:", scores[0])
	fmt.Println("total items:", len(scores))

	var empty [3]int
	fmt.Println("zero value:", empty)

	backup := scores
	backup[0] = 0
	fmt.Println("scores:", scores, "backup:", backup)
	fmt.Println("equal?", scores == [3]int{80, 90, 100})
}

Code breakdown

  1. Literalscores := [3]int{80, 90, 100}

    The type is [3]int and all three slots are filled. Listing four values would be a compile error.

  2. Index and lengthfmt.Println("first score:", scores[0])

    The first element lives at index 0, so this prints 80. On the next line len(scores) returns 3, which is already known from the type.

  3. Zero valuevar empty [3]int

    Declared without values, it holds three int zero values and prints as [0 0 0].

  4. Copy on assignmentbackup := scores

    All three elements are copied into backup, so backup[0] = 0 changes only backup. The output shows scores as [80 90 100] and backup as [0 90 100].

  5. Comparisonscores == [3]int{80, 90, 100}

    Arrays of the same type are compared element by element; all match, so the result is true. Comparing with a [4]int would not compile.

You should see
[80 90 100]
first score: 80
total items: 3
zero value: [0 0 0]
scores: [80 90 100] backup: [0 90 100]
equal? true

Copies vs pointers, indexed literals and 2D arrays

When a function really must change the caller's array, pass a *[3]int pointer: call it with &nums, and inside the function a[0] works because Go dereferences the pointer for you. Also remember that passing a large array such as [100000]int by value copies it on every call, which can be slow. The snippet also shows an indexed literal and an array of arrays used as a grid.

arrays_more.go
package main

import "fmt"

func resetCopy(a [3]int) {
	a[0] = 0
}

func resetReal(a *[3]int) {
	a[0] = 0
}

func main() {
	nums := [3]int{7, 8, 9}
	resetCopy(nums)
	fmt.Println(nums) // [7 8 9]
	resetReal(&nums)
	fmt.Println(nums) // [0 8 9]

	primes := [...]int{2, 3, 5, 7}
	slots := [5]string{1: "B", 3: "D"}
	fmt.Printf("%d %d %q\n", len(primes), len(slots), slots) // 4 5 ["" "B" "" "D" ""]

	var board [3][3]string
	board[1][1] = "X"
	fmt.Printf("%q\n", board[1]) // ["" "X" ""]
}

In real projects

Where this shows up in real projects

Where the amount of data can change, such as user lists and search results, Go programmers use slices, which the next lesson covers. Arrays show up where the size is part of the data's meaning. crypto/sha256's sha256.Sum256(data) returns a [32]byte, because a SHA-256 hash is always 32 bytes. An RGB colour as [3]uint8, an IPv4 address as [4]byte and a tic-tac-toe board as [3][3]string are similar cases.

Because arrays are comparable, they can be map keys, which is genuinely handy. You might store file hashes in a map[[32]byte]string to find duplicate files, or use [2]int{x, y} as a key to remember visited cells in a grid game. A slice cannot be compared with ==, so it can never be a map key. Also keep in mind that an array inside a struct is copied every time the struct is copied.

Common mistakes

Common mistakes

1. Looping with <= len()

for i := 0; i <= len(scores); i++ reads scores[3] on its last pass and stops with "panic: runtime error: index out of range [3] with length 3". Use i < len(scores), or better, for i := range scores, which can never step past the end.

2. Editing an array parameter and expecting the caller to see it

As the problem section showed, the function only receives a copy. Return the edited array and store it, as in scores = resetFirst(scores), or pass a *[3]int pointer. If the amount of data can vary, a slice is the more natural choice anyway.

3. Treating arrays of different lengths as one type

func total(a [5]int) int cannot be called with a [3]int, so you would need one function per length. When you must accept several lengths, change the parameter to a []int slice and pass arr[:].

Best practices

Best practices

  • Choose an array only when the size is part of the data's meaning (a hash, a colour, a coordinate) and prefer slices everywhere else.
  • Never hard-code a number like 3 in loops; use len(a) or for i := range a so the code follows the type if the length changes.
  • If a large array is passed around often, mind the cost of copying it and pass a pointer or an a[:] slice instead.
  • When a function produces a modified array, make that obvious in the signature by returning the new array.

Mini challenge

Mini challenge: a week of temperatures

Store a week of temperatures in a [7]float64 and write functions for the average and the hottest day, plus one that returns an edited copy.

  • average([7]float64) float64 returns the mean
  • hottest([7]float64) (day string, temp float64) uses a [7]string of day names
  • clearWeekend([7]float64) [7]float64 returns a copy with Sat and Sun set to 0
  • main() prints the week array afterwards to prove it did not change
weather.go
package main

import "fmt"

var days = [7]string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}

func average(temps [7]float64) float64 {
	// TODO: add every value and divide by len(temps)
	return 0
}

func hottest(temps [7]float64) (day string, temp float64) {
	// TODO: remember the index of the highest value
	return "", 0
}

func clearWeekend(temps [7]float64) [7]float64 {
	// TODO: set index 5 and 6 to 0 and return the copy
	return temps
}

func main() {
	week := [7]float64{31.5, 33, 34.5, 32, 36, 35.5, 30}
	// TODO: print the average with %.2f, the hottest day,
	// then week and clearWeekend(week) on separate lines
	fmt.Println(week)
}

Expected: average: 33.21 hottest: Fri 36 week: [31.5 33 34.5 32 36 35.5 30] weekdays: [31.5 33 34.5 32 36 0 0]

Show hint

In hottest(), start with best := 0 and inside for i := range temps set best = i whenever temps[i] > temps[best]. clearWeekend()'s parameter is already a copy, so you can edit it directly and return it.

Show solution
weather.go
package main

import "fmt"

var days = [7]string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}

func average(temps [7]float64) float64 {
	total := 0.0
	for _, t := range temps {
		total += t
	}
	return total / float64(len(temps))
}

func hottest(temps [7]float64) (day string, temp float64) {
	best := 0
	for i := range temps {
		if temps[i] > temps[best] {
			best = i
		}
	}
	return days[best], temps[best]
}

func clearWeekend(temps [7]float64) [7]float64 {
	temps[5], temps[6] = 0, 0
	return temps
}

func main() {
	week := [7]float64{31.5, 33, 34.5, 32, 36, 35.5, 30}
	fmt.Printf("average: %.2f\n", average(week))

	day, temp := hottest(week)
	fmt.Println("hottest:", day, temp)

	weekdays := clearWeekend(week)
	fmt.Println("week:    ", week)
	fmt.Println("weekdays:", weekdays)
}

Quick quiz 1 / 3

What does a := [2]int{1, 2}; b := a; b[1] = 9; fmt.Println(a, b) print?

Quick quiz 2 / 3

After scores := [3]int{80, 90, 100}, what happens with fmt.Println(scores[3])?

Quick quiz 3 / 3

Which data fits an array better than a slice?

What to remember

  • In [N]T, N is a constant and part of the type, so [3]int and [4]int are different types.
  • A declared array starts with zero values, and [...] lets the compiler count the length.
  • Assigning, passing or returning an array copies every element.
  • A bad constant index is a compile error, a bad runtime index panics, and comparable arrays work with == and as map keys.

A Tour of Go — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Arrays | Thuta Learning