Go Arrays
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 Arrays
Go has multiple ways for declaring arrays:
Syntax
var a = [length]type{values} // length is defined.
b := [length]type{values} // length is defined.
var c = [...]type{values} // length is inferred.
d := [...]type{values} // length is inferred.
Note: In Go, arrays have a fixed size. The length of the array is either defined explicitly or is inferred.
Example
This example shows how to declare an array with defined length:
package main
import ("fmt")
func main() {
var a = [3]int{1,2,3}
b := [5]int{4,5,6,7,8}
fmt.Println(a)
fmt.Println(b)
}
Result:
[1 2 3]
[4 5 6 7 8]
Example
This example shows how to declare an array with inferred length:
package main
import ("fmt")
func main() {
var a = [...]int{1,2,3}
b := [...]int{4,5,6,7,8}
fmt.Println(a)
fmt.Println(b)
}
Result:
[1 2 3]
[4 5 6 7 8]
Access Elements of an Array
You 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])
}
Result:
10
30
Change Elements of an Array
It is also possible to change the value of a specific element in the array.
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]
Array Initialization
If an array or one of its elements has not been initialized in the code, it is assigned the default value of its type. This is the same as what happens when you declare variables without initial values assigned to them.
Example
package main
import ("fmt")
func main() {
a := [3]int{} //not initialized
b := [3]int{1,2} //partially initialized
c := [3]int{1,2,3} //fully initialized
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}
Result:
[0 0 0]
[1 2 0]
[1 2 3]
Initialize Specific Elements
It is possible to initialize only specific elements in an array.
Example
package main
import ("fmt")
func main() {
a := [4]int{1:10,2:40}
fmt.Println(a)
}
Result:
[0 10 40 0]
Example Explained
The array above has 4 elements.
1:10means assigning10to index1(second element).2:40means assigning40to index2(third element).
Length of an Array
The len() function is used to find the length of an array:
Example
package main
import ("fmt")
func main() {
a := [4]int{1,2,3,4}
b := [...]int{1,2,3,4,5,6}
fmt.Println(len(a))
fmt.Println(len(b))
}
Result:
4
6

