Go Arrays Tutorial

In this Go tutorial we learn about a data container that can store multiple values, an array.

We learn how to declare empty arrays or initialize them with values, how to access array values one by one or in a loop and how to change array values.

Lastly, we learn about multi-dimensional arrays and how to pass arrays as function arguments.

What is an array

An array is a data container that can store multiple values instead of just a single value like a variable.

As an example, consider a list of groceries. It would be cumbersome to store items in our list as separate variables and even worse to access them one by one.

Example:
func main() {

    groceryItem1 := "Bread"
    groceryItem2 := "Milk"
    groceryItem3 := "Cheese"

}

Instead, we use an array that’s stored in a variable and can be accessed by a single identifier.

If we’re working with a larger number of values, it’s better to store them in an array instead of declaring many variables. Arrays are stored together, in sequence, in memory and are accessed faster.

How to declare an array

We can declare an empty array and add values to it later on.

Syntax:
 var array_name [size] array_type

Note that the array is declared by using the var keyword.

The array size is the amount of elements the array can store. Meaning, if our grocery list has 3 items, we would specify that between the square brackets.

Example:
package main

func main() {

    var groceryList [3] string
}

In the example above, we create an array called groceryList that can store 3 string elements.

How to initialize an array with values

If we know the values we want to store beforehand, we can initialize the array with them immediatly.

To do this, we add the assignment operator between the array name and its size to indicate to the compiler that we’re going to add values.

For the values themselves, we simply add a code block with open and close curly braces and write our values, separated by a comma, in there.

Syntax:
var array_name = [size] array_type {

    value1,
    value2,
    ...
}
Example:
package main

func main() {

    var groceryList = [3] string {

        "Bread",
        "Milk",
        "Cheese",
    }
}

When we initialize an array with values, we don’t have to explicitly state the size. The compiler can infer the size by counting the values we add.

Example:
package main

func main() {

    var groceryList = [] string {

        "Bread",
        "Milk",
        "Cheese",
    }
}

The compiler won’t raise an error if we leave the size as blank.

How to access single array element values

An array is organized like a table with a single row, but many columns.

As an example, let’s consider a table with characters that form the word “HELLO”. The array would have each character in their own cell in a column.

HELLO

Each cell of the table is an element in our array. The array also has an numerical index to identify the location of each element in the array.

01234
HELLO

Note that numerical indexes always start at 0 and not 1.

When we want to access an array element, we use this index number between square brackets to refer to the element.

Syntax:
 array_name[index]
Example:
package main

import "fmt"

func main() {

    var groceryList = [] string {

        "Bread",
        "Milk",
        "Cheese",
    }

    fmt.Println( groceryList[0] )
}

In the example above, we access the first element in the array, the element at index 0.

How to access array element values with a loop

Because we have multiple values in an array, it makes sense to access them with a loop.

Example:
package main

import "fmt"

func main() {

    var groceryList = [] string {

        "Bread",
        "Milk",
        "Cheese",
    }

    for i:=0; i<3; i++ {

        fmt.Println( groceryList[i] )
    }

}

Because we know beforehand how many elements there are in the array we can use a counter controlled for loop.

We then use our counter as the array index so that each time the loop iterates, the counter increases, going through each element in the array.

How to access array element values with a loop and the range keyword

Go provides us with the range keyword to make it easier to traverse list structures (like arrays).

The for loop with the range keyword in Go would be similar to foreach loops in a language like C#.

We assign the array as a range to two variables inline. One will hold the index, and the other will hold the actual value at that index.

Syntax:
for index, element_value := range array_name {

    // use index
    // use elementValue
}
Example:
package main

import "fmt"

func main() {

    var groceryList = [] string {

        "Bread",
        "Milk",
        "Cheese",
    }

    for i, item := range groceryList {

        fmt.Printf("[%d] %s\n", i, item)
    }
}

In the example above, i is our index and item is the value at that index.

How to change array element values

Arrays in Go are mutable, which means that we can change their values at runtime.

To change an array element’s value, we simply assign a new value to the element at a specific index with the assignment operator.

Syntax:
 array_name[index] = new_value
Example:
package main

import "fmt"

func main() {

    var groceryList = [] string {

        "Bread",
        "Milk",
        "Cheese",
    }

    // mutate value
    groceryList[0] = "Apples"

    for i, item := range groceryList {

        fmt.Printf("[%d] %s\n", i, item)
    }
}

In the example above, we change the value of the first element from ‘Bread’ to ‘Apples’.

Multi-dimensional arrays

If a normal array is a table with a single row but many columns, a multi-dimensional array would be a table with multiple rows and columns.

A multi-dimensional array would look like this:

 Column 0Column 1Column 2
Row 0a[0][0]a[0][1]a[0][2]
Row 1a[1][0]a[1][1]a[1][2]
Row 2a[2][0]a[2][1]a[2][2]

To declare a multi-dimensional array, we simply add another index after the first.

Syntax:
 var array_name [size1][size2][...] array_type

When we don’t initialize the array with values, we don’t use the assignment operator.

Example:
package main

func main() {

    var employee [2][2] string
}

When we initialize a multi-dimensional array with values, we add each dimension’s values in another set of open and close curly braces.

Syntax:
var array_name [size1][size2][...] array_type {

    { value1, value2, ... }, // dimension (row) 1
    { value1, value2, ... }, // dimension (row) 2
}

Each dimension is separated by a comma.

Example:
package main

func main() {

    var employee = [2][2] string {

        { "John Doe", "Jane Doe" },
        { "Analyst", "Sysadmin" },
    }
}

In the example above, our first dimension (row) contains the names of employees and our second dimension contains their respective job titles.

To access a multi-dimensional array we specify both indeces, with the first representing the dimension and the second representing the index in the dimension.

Syntax:
 array_name[dimension][index]
Example:
package main

import "fmt"

func main() {

    var employee = [2][2] string {

        { "John Doe", "Jane Doe" },
        { "Analyst", "Sysadmin" },
    }

    fmt.Println(employee[0][1])
}

In the example above, the compiler will go into the first dimension (at element 0) and access the second value (at element 1), which is “Jane Doe”.

To access multi-dimensional array elements in a loop, we can simply nest a loop for each dimension.

Syntax:
for i := 0; i < size1; i++ {

    for j := 0; j < size2; j++ {

        // i is the index of dimension 1
        // j is the index of dimension 2
    }
}
Example:
package main

import "fmt"

func main() {

    var groceryList = [2][2] string {

        { "Milk", "Bread" },
        { "Soap", "Washing Powder" },
    }

    for i:=0; i<2; i++ {
        for j:=0; j<2; j++ {

            fmt.Printf("[%d][%d] %s\n", i, j, groceryList[i][j])
        }
    }
}

How to pass arrays to functions as arguments

Go allows us to pass whole arrays to functions as arguments.

To do this we simply add an array parameter with the following syntax.

Syntax:
func function_name( array_name[] type ) return_type {

    // body
}
Example:
package main

import "fmt"

func main() {

    var greeting = [] string {
        "Hello there",
        "Greetings",
    }

    consoleLog(greeting)
}

func consoleLog(msgs[] string) {

    // get the number of
    // elements in the array
    alen := len(msgs)

    for i:=0; i<alen; i++ {
        fmt.Println(msgs[i])
    }
}

In the example above, we use the len(array_name) function to get the amount of elements in the array to loop through.

Summary: Points to remember

  • An array is a variable that can store multiple values.
  • A standard array can be considered as a table with a single row, but many columns.
  • A multi-dimensional array can be considered as a table with many rows and many columns.
  • Empty arrays are declared without the assignment operator and must have a size number.
  • Arrays that are initialized with values may omit the size, but must contain a code block with comma separated values.
  • Arrays have built-in numerical indeces to enable access and mutation by specifying the index between square brackets.
  • Arrays can be accessed through a for loop and through a for loop with the range keyword.
  • We can pass arrays to functions as arguments by adding arrays to functions as parameters.