In programming, we often work with collections of related data. Arrays are one data structure that allows you to create collections of related data and perform operations on it.
In go, we can create arrays of related types, including int, string, floats, and more.
The crux of this guide is to help you get started working with arrays using the Go programming language.
Define Array
To create an array in Go, we start by defining the array name, followed by the length of the array in square brackets, and finally, the data type held by the array.
We can express the syntax as:
Here, the length refers to the number of elements to store in the defined array.
For example, the following snippet creates an array called my_array that stores 5 elements of type string:
"MySQL",
"MongoDB",
"Oracle",
"Elasticsearch",
"SQLite",
}
Note that a comma separates each element in the array, including the last element.
Indexing Arrays
Once an array is declared, you can access individual elements using its index. Array indexing in Go starts at index 0. This means that the first element in the array is index 0, and the last element in the array is the length of the array minus 1.
For example, to access the first element in the my_array array, we can do:
We pass the index of the element we wish to access using square brackets.
The code above should return the first element in the array as:
MySQL
Print Array Items.
We can use the Println() method from the fmt package to print all items in the array. For example:
The output is as shown:
Iterate Over Array
We can iterate over each items of the array using a for loop. For example, to iterate over each item of the array, we can do:
fmt.Println(my_array[i])
}
We create a for loop starting from index 0 to the length of the array. We then use each index iteration to return the item at that index.
The resulting output.
MongoDB
Oracle
Elasticsearch
SQLite
If you do not know the length of the array, you can use the len function as:
fmt.Println(my_array[i])
}
The code above will iterate the elements of the array based on its length.
Conclusion
This guide covers the basics of working and printing elements of the array using for loops.