golang arrays can hold multiple values. The minimum elements of an array is zero, but they usually have two or more. Each element in an array has a unique index.

The index starts at zero (0). That means to access the first element of an array, you need to use the zeroth index.

Download PDF

Arrays in golang

Example

The program below is an example of an array loop in golang.
The array we define has several elements. We print the first item with the zeroth index.

1
2
3
4
5
6
7
8
9
10
package main

import "fmt"

func main() {
var a = []int64{ 1,2,3,4 }

fmt.Printf("First element %d", a[0] )
fmt.Printf("Second element %d", a[1] )
}

Upon running this program it will output the first (1) and second (2) element of the array. They are referenced by the zeroth and first index. In short: computers start counting from 0.

This program will output:

1
2
First element: 1
Second element: 2

The index should not be larger than the array, that could throw an error or unexpected results.

Video tutorial

Video below

Exercises

  1. Create an array with the number 0 to 10
  2. Create an array of strings with names

Download Answers