Go Arrays
Arrays are used to store multiple values of the same type in a single variable, instead of declaring separate variables for each value.
Declare an Array
In Go, there are two ways to declare an array:
1. With the var
keyword:
Syntax
package main
import ("fmt")
func main() {
var arr1 = [3]int{1,2,3}
arr2 := [5]int{4,5,6,7,8}
fmt.Println(arr1)
fmt.Println(arr2)
}
[1 2 3]
[4 5 6 7 8]
Example
This example declares two arrays (arr1 and arr2) with inferred lengths:
package main
import ("fmt")
func main() {
var arr1 = [...]int{1,2,3}
arr2 := [...]int{4,5,6,7,8}
fmt.Println(arr1)
fmt.Println(arr2)
}
Example
This example declares an array of strings:
package main
import ("fmt")
func main() {
var cars = [4]string{"Volvo", "BMW", "Ford", "Mazda"}
fmt.Print(cars)
}
Access Elements of an Array
You can access a specific array element by referring to the index number.
In Go, array indexes start at 0. That means that [0] is the first element, [1] is the second element, etc.
Example
This example shows how to access the first and third elements in the prices array:
package main
import ("fmt")
func main() {
prices := [3]int{10,20,30}
fmt.Println(prices[0])
fmt.Println(prices[2])
}
Change Elements of an Array
You can also change the value of a specific array element by referring to the index number.
Example
This example shows how to change the value of the third element in the prices array:
package main
import ("fmt")
func main() {
prices := [3]int{10,20,30}
prices[2] = 50
fmt.Println(prices)
}
Result:
[10 20 50]
Find the Length of an Array
The len()
function is used to find the length of an array:
Example
package main
import ("fmt")
func main() {
arr1 := [4]string{"Volvo", "BMW", "Ford", "Mazda"}
arr2 := [...]int{1,2,3,4,5,6}
fmt.Println(len(arr1))
fmt.Println(len(arr2))
}
Result:
46