Working with Arrays in Go

11.09.2021

Intro

Arrays are a fixed list of variables all with the same size. For example, we can have an array of 3 integers, or 4 strings, but we cannot mix them. Because arrays are fixed, their size cannot change, they are not often used directly. Instead, developers will use slices. But, arrays are a good introduction to slices. In this article, we will learn how to use Arrays in Go.

Creating Arrays in Go

We can created arrays using the following.

var list [3]int

This will create a list of 3 integers. We did not initialize the values, so all values will default to 0.

To initialize the values, we can do the following.

var list [3]int = {1, 2, 3}

We can also let go infer the size from the declared value using the ... operator. Here is an example.

var list [...] = {1, 2, 3}

Go will automatically determine the size of 3.

Accessing Items in an Array

To access an item in an array, we can use indexing notation. Here are some examples.

fmt.Println(a[0])
fmt.Println(a[1])

We can also loop through arrays using the for...range notation.

for i, v := range a {
	fmt.Printf("%d %d \n", i, v)
}