Go Arrays
An array keeps several values of one type together under a single name. That saves you from creating a separate variable for every value.
Declare an Array
Go lets you declare an array either with the var keyword or with the := operator.
The syntax here uses var:
Example
Here the length of each array is written out: 3 for arr1 and 5 for arr2. One uses var, the other :=:
Output: Go program and captured output
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)
}
Example
Replace the length with ... and Go counts the values for you, so these two arrays end up with lengths 3 and 5:
Output: Go program and captured output
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)
}
Syntax
When you state the length yourself:
var array_name = [length]datatype{values}
Syntax
When Go works out the length for you:
var array_name = [...]datatype{values}
Access Elements of an Array
To read one element of an array, write its index number in square brackets.
Counting begins at 0, not 1, so [0] gives you the first element, [1] the second, and so on.
Example
Indexes 0 and 2 give the first and third values of prices:
Output: Go program and captured output
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
The same index notation works for writing: assign a new value to an index and that element is replaced.
Example
Assigning to prices[2] replaces the third value, 30, with 50:
Output: Go program and captured output
package main
import ("fmt")
func main() {
prices := [3]int{10, 20, 30}
prices[2] = 50
fmt.Println(prices[0])
fmt.Println(prices[2])
}
Array Initialization
Any array element you leave without a value is not really empty. Go fills it with the default value of its type, and the same goes for an array you never initialize at all.
Note: For int that value is 0; for string it is "".
Example
You can set only the positions you care about by writing index:value. Here index 1 gets 10 and index 2 gets 40, while the other three elements stay at 0:
Output: Go program and captured output
package main
import ("fmt")
func main() {
arr1 := [5]int{1:10, 2:40}
fmt.Println(arr1)
}
Find the Length of an Array
To learn how many elements an array has, pass it to the len() function.