Arrays in Golang

Arrays represent a sequence of elements of a particular type. The array is defined in the following way:

var name [number_of_elements] type

Define an Array

For example, an array of four elements of type string:

var names [4]string

With this definition, all elements of the array are initialized with default values. But you can also initialize array elements with other values:

var names = [4]string{"Docker","Kubernetes","Rust","React"}

Values are passed in curly braces separated by commas. In this case, the values cannot exceed the length of the array. In this case, the length of the array is 4, so you can't define more than five elements in curly brackets. But you can define fewer elements:

var names = [4]string{"Docker","Kubernetes"}

In this case, items that do not have a value specified will have a default value.

names := [2]string{"Docker","Kubernetes"}

If an ellipsis is specified in square brackets instead of length, the length of the array is determined based on the number of elements passed to it:

var names := [...]string{"Docker","Kubernetes"}

In this case, the length of this array is 2 as we just pass to the element.

Indices

To refer to the elements of the array, indexes are used, i.e. the numbers of the elements. In this case, the numbering starts from zero, that is, the first element will have an index of 0. The index is indicated in square brackets. From the index, you can get the value of an item, or change it:

package main

import "fmt"

func main() {
    books: = [3] string {
        "Docker", "Linux", "Rust"
    }

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

The indexes in the array act as keys that can be used to access the corresponding value. In the application, we can explicitly specify which key will correspond to which value. At the same time, numeric keys do not have to be arranged in ascending order:

books: = [3] string {
    1: "Docker",
    0: "Linux",
    2: "Rust"
}

fmt.Println(books[1])

The output should be the "Docker" book:

Docker