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.
Declaring an Array #
In Go, there are two ways to declare an array:
1. Using the var
keyword
#
var array_name = [length]datatype{values} // length defined
var array_name = [...]datatype{values} // length inferred
2. Using the :=
shorthand
#
array_name := [length]datatype{values} // length defined
array_name := [...]datatype{values} // length inferred
Note: Arrays in Go have a fixed length. The length is either explicitly defined or inferred from the number of values.
Array Examples #
Defined Length #
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)
}
Result:
[1 2 3]
[4 5 6 7 8]
Inferred Length #
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)
}
Result:
[1 2 3]
[4 5 6 7 8]
Array of Strings #
package main
import ("fmt")
func main() {
var cars = [4]string{"Volvo", "BMW", "Ford", "Mazda"}
fmt.Print(cars)
}
Result:
[Volvo BMW Ford Mazda]
Access Elements of an Array #
Array indexes start at 0
. To access elements:
package main
import ("fmt")
func main() {
prices := [3]int{10,20,30}
fmt.Println(prices[0]) // first element
fmt.Println(prices[2]) // third element
}
Result:
10
30
Change Elements of an Array #
package main
import ("fmt")
func main() {
prices := [3]int{10,20,30}
prices[2] = 50
fmt.Println(prices)
}
Result:
[10 20 50]
Array Initialization #
Uninitialized arrays are assigned default values:
package main
import ("fmt")
func main() {
arr1 := [5]int{} // not initialized
arr2 := [5]int{1,2} // partially initialized
arr3 := [5]int{1,2,3,4,5} // fully initialized
fmt.Println(arr1)
fmt.Println(arr2)
fmt.Println(arr3)
}
Result:
[0 0 0 0 0]
[1 2 0 0 0]
[1 2 3 4 5]
Initialize Specific Elements #
package main
import ("fmt")
func main() {
arr1 := [5]int{1:10,2:40}
fmt.Println(arr1)
}
Result:
[0 10 40 0 0]
Explanation:
1:10
assigns 10 to index 1 (second element)2:40
assigns 40 to index 2 (third element)
Find the Length of an Array #
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:
4
6
Tip: The len()
function returns the number of elements in an array.