DMarlon Studio

Lesson 9 · 9 of 20

Arrays · Go

Store several values of one type in a Go array: fixed length, indexes, len, looping with for, copying on assignment and comparing with ==.

Go · Arrays in DMarlon Studio: the example's code and its output in the terminal

An array holds a fixed number of values of the same type. var rainfall [7]float64 sets aside seven numbers, one per day, and they all start at their zero value, 0. The length is part of the type: [7]float64 and [8]float64 are different types.

Each element is reached by its index, which starts at 0: rainfall[3] = 11 is the fourth day, Thursday. fmt.Println prints the whole array in square brackets. In a literal, [...] lets Go count the elements: days has 7, as len(days) says.

The classic for walks the indexes from 0 to len(rainfall)-1: it adds the rain into total and keeps in wettest the index of the wettest day. Since days follows the same order, days[wettest] gives its name: Thu.

Assigning an array copies all of it: backup := rainfall creates another array, and changing backup[0] leaves the original alone. That is why == gives false: two arrays of the same type can be compared, and they are equal only if every element is. In practice slices, from the next lesson, are used more, because they can grow.

Code · main.go

package mainimport "fmt"func main() {	// An array has a fixed length, and it is part of its type.	var rainfall [7]float64	rainfall[0] = 2.5	rainfall[3] = 11	rainfall[6] = 4.25	fmt.Println("Rainfall:", rainfall)	// [...] lets Go count the elements of the literal.	days := [...]string{"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"}	fmt.Println("Days in a week:", len(days))	total, wettest := 0.0, 0	for i := 0; i < len(rainfall); i++ {		total += rainfall[i]		if rainfall[i] > rainfall[wettest] {			wettest = i		}	}	fmt.Printf("Total: %.2f mm\n", total)	fmt.Println("Wettest day:", days[wettest])	// Assigning an array copies all of it.	backup := rainfall	backup[0] = 99	fmt.Println("Monday:", rainfall[0], "in the copy:", backup[0])	// Arrays of the same type can be compared with ==.	fmt.Println("Same data?", backup == rainfall)}

Output · go run main.go

Rainfall: [2.5 0 0 11 0 0 4.25]
Days in a week: 7
Total: 17.75 mm
Wettest day: Thu
Monday: 2.5 in the copy: 99
Same data? false

Key points

  • [n]type is an array of n elements; n never changes.
  • Indexes go from 0 to len(a)-1.
  • [...] counts the elements of the literal.
  • Assigning an array copies every element.
  • Two arrays of the same type compare with ==.

Exercise

Add a [7]float64 array with the week's temperatures and print the average and the coldest day, with its name taken from days.