Arrays are consecutive storage of the same data-type. In this post, we will see how arrays work in Golang.
Declaration of an Array
To declare an array in Go we first give its name, then size, then type as shown below.
var ids [7]int // an int array of size 7
Initialization of an Array
Let’s see how to initialize an array. If we don’t initialize it will take zero-value for all values.
package main
import "fmt"
func main() {
var names []string
fmt.Println(names) // prints [] because the size is not specified
var people [3]string
fmt.Println(people) // prints [ ] because the size is 2
}
Here zero-value for a string is an empty string “”.
Array access by index
Array elements can be accessed by their index as shown below.
package main
import "fmt"
func main() {
var nums = [4]int{1, 2, 3, 4} // init
fmt.Println(nums[0]) // 1
}
Iterating over Array Elements
To iterate we simple loop over the entire array. We here use a specific keyword called range which helps make this task a lot easier.
package main
import "fmt"
func main() {
evens := [3]int{2, 4, 8}
for i, v := range evens { // here i is index and v is value
fmt.Println(i, v)
}
// outputs
// 0 2
// 1 4
// 2 8
}
Multi-Dimensional Arrays in Go
Multi-Dimensional arrays can be used in Go just like any other array. Below is an example.
package main
import "fmt"
func main() {
arr := [2][2]int{
{1, 2},
{3, 4}, // last comma should be there
}
fmt.Println(arr) // [[1 2] [3 4]]
// Iterating over each element
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
fmt.Printf("arr[%d][%d] = %d\n", i, j, arr[i][j] )
}
}
// output:
// arr[0][0] = 1
// arr[0][1] = 2
// arr[1][0] = 3
// arr[1][1] = 4
}