Elements in the arrays are indexed, allowing you to access and update each element based on its position in the collection.
This article will cover the basics of working with arrays in the Go programming language.
Declaring an Array
We can declare an array using the syntax shown below:
We start by defining the name of the array; we then set the length of the array, which dictates how many elements we can store in that array. Finally, we set the data type held by the array.
For example, the snippet below creates an array of type strings.
This will create an array called “my_array” of length 5 holding string data types.
Array Initialization – Ellipses
You can also use ellipses to when initializing an array. The array replaces the length of the array and lets the compiler determine the length based on the number of elements in the array.
An example is as shown:
import "fmt"
func main() {
my_array := [...]string{"a", "b", "c", "d", "e"}
fmt.Println(my_array)
}
The elements in it determine the length of the array above. To get the length of an array, use the len() method as:
Output
Array Initialization – Array Literal
We can assign values to an array during declaration. For example, the snippet below creates an array with string values:
The above method of array declaration is known as an array literal. Here, we define the name of the array followed by its length, data type, and the elements it holds.
If you have an already declared array, you can assign values to it using the index. Keep in mind that indexing of arrays starts at 0.
Consider the example below:
my_array[0] = "a"
my_array[1] = "b"
In the above example, we declare an array called my_array. We then use the square brackets to assign values to the array at a specific index.
If we print the array:
We get an output as:
To assign values to the rest of the indexes, we can use the square bracket notation as:
my_array[3] = "d"
my_array[4] = "e"
If we check the new array, we should get an output as:
Ensure you stay within the bounds of the array. For example, trying to access a value at index 5, which does not exist, results in an error.
invalid array index 5 (out of bounds for 5-element array)
Array Initialization – Set Elements at a specific index
We can also set values for specific indexes during array initialization. For example, to assign a value to index 0, 3, and 4, we can do:
This will set values for index 0, 3, and 4 leaving the other indexes empty. If we print the array, we should get an output as:
An output:
Accessing Array Elements
We can also access individual elements of an array using the square brackets. For example, to get the element stored at index 0, we can do:
The above syntax should return the code allocated at the specified index.
a
Conclusion
This guide covers the basics of working with arrays in the go programming language. Thanks for reading!