Arrays provide a way for us to store many values of the same type under the same name. These individual values are found within the array via their index.
The format for declaring an array is:
var arrayName [elementCount] dataType
We can set access the individual elements using the index:
arrayName[index]
Indexing begins at zero
Indexing in Golang, like many other languages, begins at zero ($0$). An array named names with $3$ elements will allow us to access these elements using names[0], names[1] and names[2] respectively:
package main
import "fmt"
func main() {
var names [3]string
names[0] = "John"
names[1] = "James"
names[2] = "Peter"
fmt.Println("names[0] = ", names[0])
fmt.Println("names[1] = ", names[1])
fmt.Println("names[2] = ", names[2])
}
We can also declare and initialize the values of the names variable in a single statement using shorthand notation:
package main
import "fmt"
func main() {
names := [...]string{
"John", "James", "Peter",
}
fmt.Println("names[0] = ", names[0])
fmt.Println("names[1] = ", names[1])
fmt.Println("names[2] = ", names[2])
fmt.Printf("The array has %d values\n", len(names))
}
We can use […]names to make the compiler count the number of values in the array instead of us having to type [3]names when asking for an array that can store $3$ values.
We use the len function to get the number of values in the array. The syntax is len(arrayName).
Array values will be zeroed based on the zero-value of the datatype used. We can initialize the first and last $2$ values in the shorthand notation by specifying the index:
package main
import "fmt"
func main() {
ages := [...]int{40, 7: 5, 10}
fmt.Println(ages)
}
Here we set the first value and then set the value at index 7 and finally the last value in the array.
Fixed size
Unlike slices, arrays in Go are of a fixed size. Once we declare them, we cannot change how many values can be stored in the array.
package main
import "fmt"
func main() {
ages := [...]int{12, 14, 13}
// editing the second age value in the array
ages[1] = 5
// printing the ages
fmt.Println("ages[0] = ", ages[0])
fmt.Println("ages[1] = ", ages[1])
fmt.Println("ages[2] = ", ages[2])
// the compiler will complain that the index 3 is out of bounds
fmt.Println("ages[3] = ", ages[3])
}
Multi-dimensional arrays
We can nest an array within an array:
package main
import "fmt"
func main() {
arrayOfArrays := [2][4]string{
{"Key1", "Value1", "Metadata1", "List1"},
{"Key2", "Value2", "Metadata2", "List2"},
}
fmt.Println(arrayOfArrays)
}
The [2] tells the compiler to allocate for $2$ arrays within the outer array and the [4]string indicates that $4$ string values should be in each of the inner arrays.