golang

Golang Array

Arrays are the building blocks of most programming language. They allow you to store a collection of related data. Arrays are of fixed length, meaning they can only hold a specified number of elements.

Throughout this guide, we will discuss how to work with arrays in the Go programming language.

Golang Declare Array

We can declare an array by specifying the variable name, the array length and the data type of the elements the array will hold.

An example syntax is shown:

var array_name[length]data_type

You can declare and initialize the array using the syntax as shown below:

array_name := [length]data_type{elements}

For example, to declare an array without initializing it, we can do:

package main
funcmain() {
    varmy_array [5]string
}

If you want to add elements during array declaration, you can run the code as:

package main
funcmain() {
    my_array := [5]string{"MySQL","MongoDB","Oracle",}
}

The above method is far shorter and more readable.

Golang Infer Array Length

Sometimes, you may want Go to allocate the length of the array based on the items in the array. To do this, we use the ellipsis operator (…) instead of the actual length of the array. An example is as shown:

package main
funcmain() {
    my_array := [...]string{"MySQL","MongoDB","Oracle",}
}

Here, we replace the length of the array with ellipsis operator. Go will determine the number of elements in the array and use that as the array length.

Golang Access Array Elements

Arrays uses indexes to access, delete, and update values. Array indexing in Go starts at 0. This means that the first element in the array is at index 0.

To access the element in an array, we use the array name and then the index of the element to access enclosed in a pair of square brackets.

An example:

package main
import "fmt"
funcmain() {
    my_array := [...]string{"MySQL", "MongoDB", "Oracle"}
    fmt.Println(my_array[0])
}

The above returns the first element in the array. An example output is as shown:

MySQL

Golang Assign Array Elements

If you declare an empty array, you can assign items to the array using the index. An example is as shown below:

package main
import "fmt"
funcmain() {
    varmy_array [5]string
    my_array[0] = "MySQL"
    my_array[1] = "MongoDB"
    my_array[2] = "Oracle"
    my_array[3] = "SQLite"
    my_array[4] = "CockroachDB"
    fmt.Println(my_array)

}

In the example above, we declare an empty array with the length of 5. We then use the array indexes to add elements to the array.

Keep in mind not to go out of the bounds of the array index. For example, if you try to access index 5, in the example array above, the compiler will return an error. This is because the array does not have an index 5.

Example:

my_array[5] = "PostgreSQL"

The code above returns an out of bounds error :

invalid array index 5 (out of bounds for 5-element array)

Golang Iterate Over Array

In Go, we can iterate over the items of an array using a for loop and the range operator. For example:

package main
import "fmt"
funcmain() {
    varmy_array [5]string
    my_array[0] = "MySQL"
    my_array[1] = "MongoDB"
    my_array[2] = "Oracle"
    my_array[3] = "SQLite"
    my_array[4] = "CockroachDB"

    for index, value := rangemy_array {
        fmt.Printf("Index: %d Value:%s\n", index, value)
    }
}

The code above should iterate over an array and return each element at a specific index. The resulting output is as shown:

Index: 0 Value: MySQL

Index: 1 Value: MongoDB

Index: 2 Value: Oracle

Index: 3 Value: SQLite

Index: 4 Value: CockroachDB

Golang Array Length

You can determine the length of an array using the len method. It takes an array as the argument and returns the length of the array. Keep in mind that the length of the array is the total number of elements an array can hold.

An example code is shown:

fmt.Println("Array Length: ", len(my_array))

This should return the length of the array as:

Array Length: 5

Golang Multi-Dimensional Arrays

We can create a multi-dimensional array by adding a pair of square and curly braces.

An example of a multi-dimensional array is as shown:

package main
import "fmt"
funcmain() {
    my_array :=  [5][5]int{
        {1,2,3,4,5},
        {6,7,8,9,10},
        {11,12,13,14,15},
        {16,17,18,19,20},
        {21,22,23,24,25},
    }
    fmt.Println(my_array)
}

The above example creates a multi-dimensional array. Once we print the array, we should get an output as:

[[1 2 3 4 5] [6 7 8 9 10] [11 12 13 14 15] [16 17 18 19 20] [21 22 23 24 25]]

We can iterate over a multi-dimensional array as shown:

for x := 0; x < 5; x++ {
    for y := 0; y < 5; y++ {
        fmt.Println(my_array[x][y])
    }
}

The code above will iterate over each index of the outside array and corresponding inner array. It keeps repeating this until it gets to the end.

Conclusion

In this article, we covered the basics of working with array data types in Go. Check out our other Go tutorials to explore more.

Happy coding!!

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list