O'Reilly logo

Introducing Go by Caleb Doxsey

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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:

package main

import "fmt"

func main() {
    var x [5]int
    x[4] = 100
    fmt.Println(x)
}

You should see this:

[0 0 0 0 100]

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:

func main() {
    var x [5]float64
    x[0] = 98
    x[1] = 93
    x[2] = 77
    x[3] = 82
    x[4] = 83

    var total float64 = 0
    for i := 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:

  1. First, we create an array of length 5 to hold our test scores, then we fill up each element with a grade.
  2. Next, we set up a for loop to compute the total score.
  3. 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, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required