ZetCode

Go array

last modified July 9, 2020

Go array tutorial shows how to work with arrays in Golang.

An array is a collection of elements of a single data type. An array holds a fixed number of elements, and it cannot grow or shrink.

Elements of an array are accessed through indexes. The first index is 0. By default, empty arrays are initialized with zero values (0, 0.0, false, or "").

The len function returns the length of the array.

Go declare array

var a[n]T

We declare an array of length n and having type T.

var a[5]int

Here we declare an array of five integers.

a := [5]int{1, 2, 3, 4, 5}

This is a shorthand declaration and initialization of a Go array.

Go array initialization

The following example shows how to initialize an array in Go.

array_init.go
package main

import "fmt"

func main() {

    var vals [2]int
    fmt.Println(vals)

    vals[0] = 1
    vals[1] = 2
    fmt.Println(vals)
}

In the example, we declare an array of integers; the array can hold two elements.

var vals [2]int
fmt.Println(vals)

The [2]int is the whole type, including the size number. At the beginning, the array contains 0s.

vals[0] = 1
vals[1] = 2
fmt.Println(vals)

We assign two values to the array.

$ go run array_init.go
[0 0]
[1 2]

This is the output.

Go array literal

Golang has array literals; we can specify the elements of the array between {} brackets.

array_init2.go
package main

import "fmt"

func main() {

    vals := [5]int{1, 2, 3, 4, 5}
    fmt.Println(vals)

    vals2 := [5]int{1, 2, 3}
    fmt.Println(vals2)
}

In the example, we define two arrays with array literals.

vals := [5]int{1, 2, 3, 4, 5}

The first array has five elements; all elements are initialized between {} brackets.

vals2 := [5]int{1, 2, 3}

Here we provide only three out of five elements; the rest are initialized to 0.

$ go run array_init2.go
[1 2 3 4 5]
[1 2 3 0 0]

This is the output.

In the array literal, we can provide the index of the element.

array_init3.go
package main

import "fmt"

func main() {

    vals := [5]int{1: 6, 2: 7, 4: 9}

    fmt.Println(vals)
}

In the example, we initialize an array with array literal. The values are given their index; the rest of the array elements are given 0 value.

$ go run array_init3.go
[0 6 7 0 9]

This is the output.

Go infer array length

Go can inver the array length when using array literals. For this, we use the ellipses ... operator.

infer_length.go
package main

import "fmt"

func main() {

    vals := [...]int{ 1, 2, 3, 4, 5, 6 }
    fmt.Println(vals)
}

In the example, we use the ... in the array declaration. This tells Go to infer the length of the array from the provided array literal.

$ go run infer_length.go
[1 2 3 4 5 6]

This is the output.

Note: when we do not specify the array size and do not use the ... operator, we are in fact creating a Go slice.

To extract type information in Go, we use the reflect package.

array_slice.go
package main

import (
    "fmt"
    "reflect"
)

func main() {

    var a [5]int
    var b []int

    fmt.Println(reflect.ValueOf(a).Kind())
    fmt.Println(reflect.ValueOf(b).Kind())
}

The a is an array, while the b is a slice.

$ go run array_slice.go
array
slice

This is the output.

Go array length

The length of the array is determined with the len function.

array_length.go
package main

import "fmt"

func main() {

    words := [5]string{ "falcon", "sky", "earth", "cloud", "fox" }

    fmt.Println("There are", len(words), "words in the array")
}

In the example, we define an array of strings. We print the number of words in the array.

$ go run array_length.go
There are 5 words in the array

This is the output.

Go array indexing

Arrays are accessed with their index.

indexing.go
package main

import "fmt"

func main() {

    var words[5]string

    words[0] = "falcon"
    words[1] = "sky"
    words[2] = "earth"
    words[3] = "cloud"
    words[4] = "fox"

    fmt.Println(words[0], words[1])
    fmt.Println(words)
}

In the example, we work with an array of words.

var words[5]string

We declare an array of strings, having five elements.

words[0] = "falcon"
words[1] = "sky"
words[2] = "earth"
words[3] = "cloud"
words[4] = "fox"

We put five words into the array.

fmt.Println(words[0], words[1])

We print the first and the second element of the array.

fmt.Println(words)

We print the whole array.

$ go run indexing.go
falcon sky
[falcon sky earth cloud fox]

This is the output.

We can use the : colon character to retrieve a portion of the array.

indexing2.go
package main

import "fmt"

func main() {

    words := [...]string{ "falcon", "sky", "earth", "cloud", "fox" }

    fmt.Println(words[0:2])
    fmt.Println(words[1:])
    fmt.Println(words[:])
    fmt.Println(words[:len(words)])
}

The example prints portions of the defined array.

$ go run indexing2.go
[falcon sky]
[sky earth cloud fox]
[falcon sky earth cloud fox]
[falcon sky earth cloud fox]

This is the output.

Go array iteration

With for loops, we can iterate over array elements in Go.

array_loop.go
package main

import "fmt"

func main() {

    words := []string{ "falcon", "sky", "earth", "cloud", "fox" }

    for i := 0; i < len(words); i++ {

        fmt.Println(words[i])
    }

    for idx, e := range words {

        fmt.Println(idx, "=>", e)
    }

    j := 0

    for range words {

        fmt.Println(words[j])
        j++
    }
}

The example uses three for loop forms to iterate over an array of words.

$ go run array_loop.go
falcon
sky
earth
cloud
fox
0 => falcon
1 => sky
2 => earth
3 => cloud
4 => fox
falcon
sky
earth
cloud
fox

This is the output.

Go array is value type

Unlike in other languages, array is a value type in Go. This means that when we assign an array to a new variable or pass an array to a function, the entire array is copied.

value_type.go
package main

import "fmt"

func main() {

    vals := [...]int{ 1, 2, 3, 4, 5, 6 }
    vals2 := vals

    vals2[0] = 11
    vals2[1] = 22

    fmt.Println(vals)
    fmt.Println(vals2)
}

In the example, we define an array and assign the array to a new variable. The changes made through the second variable will not affect the original array.

$ go run value_type.go
[1 2 3 4 5 6]
[11 22 3 4 5 6]

The original array is unchanged.

Go multidimensional arrays

We can create multidimensional arrays in Go. We need additional pairs of square and curly brackets for additional array dimension.

two_dim.go
package main

import (
    "fmt"
    "math/rand"
    "time"
)

func main() {

    a := [2][2]int{

        {1, 2},
        {3, 4}, // the trailing comma is mandatory
    }

    fmt.Println(a)

    var b [2][2]int

    rand.Seed(time.Now().UnixNano())

    for i := 0; i < 2; i++ {
        for j := 0; j < 2; j++ {
            b[i][j] = rand.Intn(10)
        }
    }

    fmt.Println(b)
}

We work with two-dimensional arrays of integers.

a := [2][2]int{

    {1, 2},
    {3, 4}, // the trailing comma is mandatory
}

fmt.Println(a)

There are two nested arrays in the outer array.

var b [2][2]int

rand.Seed(time.Now().UnixNano())

for i := 0; i < 2; i++ {
    for j := 0; j < 2; j++ {
        b[i][j] = rand.Intn(10)
    }
}

fmt.Println(b)

In the second case, the array is initialized to random values. We use two for loops.

$ go run two_dim.go
[[1 2] [3 4]]
[[9 4] [1 3]]

This is a sample output.

In the following example, we create a three-dimensional array.

three_dim.go
package main

import "fmt"

func main() {

    a := [3][2][2]int{
        { {1, 2}, {3, 4} },
        { {5, 6}, {7, 8} },
        { {9, 10}, {11, 12} },
    }

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

We need three pairs of [] and {} brackets.

Go array partial assignment

An array can be partially assigned.

partial_assignment.go
package main

import "fmt"

func main() {

    var a [5]int = [5]int{10, 20, 30}

    fmt.Println(a)
}

The type and the size of the arrays must match. The elements for which there is no value will be initialized to zero.

$ go run partial_assignment.go 
[10 20 30 0 0]

The last two elements are initialized to 0.

In this tutorial, we have worked with array in Golang.

List all Go tutorials.