Chapter 5. Arrays, Slices, and Maps
In Chapter 2, we learned about Go’s basic types. In this chapter, we will look at three more built-in types: arrays, slices, and maps.
Arrays
An array is a numbered sequence of elements of a single type with a fixed length. In Go, they look like this:
var x [5]int
x is an example of an array that is composed of five ints. Try running the following program:
packagemainimport"fmt"funcmain(){varx[5]intx[4]=100fmt.Println(x)}
You should see this:
[0000100]
x[4] = 100 should be read “set the fifth element of the array x to 100.” It might seem strange that x[4] represents the fifth element instead of the fourth, but like strings, arrays are indexed starting from 0. Arrays are accessed in a similar way. We could change fmt.Println(x) to fmt.Println(x[4]) and we would get 100.
Here’s an example program that uses arrays:
funcmain(){varx[5]float64x[0]=98x[1]=93x[2]=77x[3]=82x[4]=83vartotalfloat64=0fori:=0;i<5;i++{total+=x[i]}fmt.Println(total/5)}
This program computes the average of a series of test scores. If you run it, you should see 86.6. Let’s walk through the program:
- First, we create an array of length 5 to hold our test scores, then we fill up each element with a grade.
- Next, we set up a
forloop to compute the total score. - Finally, we divide the total score by the number of elements to find the average.
This program works, but Go provides some features we can use to improve it. Specifically, ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access