Go Arrays
In Go programming language, Array is a collection of elements of the same datatype.
Go array is of fixed size. The size mentioned during the declaration or inferred during initialization is the size of the array.
The array is sequential which means that the elements of the array can be access sequentially.
Genarally in programming, an Array is used to store similar kind of values or objects where the sequence of elements matters.
For example, first 5 prime numbers [2, 3, 5, 7, 11] could be declared as an array. Here the elements belong to a same type, integer. Also the sequence matters: first prime number is 2, fourth prime number is 7, and like.
In this tutorial, we will learn how to declare an array in Golang, initialize the array and access the elements of the array.
Declaration
To declare an array in Golang, use the following syntax.
var array_name [size] datatype
where
var
is the keyword. The array we are declaring is treated as a variable.array_name
is the name that you give to the array, so that you can access its elements in the subsequent program statements.size
is the number of elements that you would like to store in the array.datatype
is the only data type of elements that is allowed for this array.
Following is an example, where we declare an array with primes
as array_name, 5
as size and int
as datatype.
example.go
package main
func main() {
var primes [5] int
}
If you run this program, you will get a warning saying that primes declared and not used
. That is just fine what we have done. We have just declared the array. We will soon initialize the array.
Set Array Values
To set array values, we can use array-index notation as shown in the following program.
example.go
package main
import "fmt"
func main() {
var primes [5]int
primes[0] = 2
primes[1] = 3
primes[2] = 5
primes[3] = 7
primes[4] = 11
fmt.Println(primes)
}
Output
[2 3 5 7 11]
Declare and Initialize
We can also declare and initialize an array in single line.
example.go
package main
import "fmt"
func main() {
primes := [5]int{2, 3, 5, 7, 11}
fmt.Println(primes)
}
Output
[2 3 5 7 11]
Access Values using Index
We can access values of an array at a specific index using array-index notation.
example.go
package main
import "fmt"
func main() {
primes := [5]int{2, 3, 5, 7, 11}
fmt.Println("Value at index 0 is : ", primes[0])
fmt.Println("Value at index 1 is : ", primes[1])
fmt.Println("Value at index 2 is : ", primes[2])
}
Output
Value at index 0 is : 2
Value at index 1 is : 3
Value at index 2 is : 5
Conclusion
In this Golang Tutorial, we learned about arrays in Go programming, how to declare arrays, initialize arrays, and access the values using index.