How to declare an array in Golang
Overview
An array is a collection of similar types of elements stored in memory. For example, a list of peoples’ ages can comprise an array. Arrays can only hold a fixed number of elements.
We can use the [] index operator to access the elements of the array. The array index starts with 0.
How to declare an array
In Golang, we can use two methods to declare an array.
1. The var keyword
We can use the var keyword to declare an array as follows:
var arrayName = [length]dataType{elements}// orvar arrayName = [...]dataType{elements}
Where:
arrayName: The name of the array.length: The length of the array. Instead of explicitly specifying the length, we can also use..., which means that the compiler will decide the length of the array based on the number of elements.dataType: The data type of the array elements.elements: The elements in the array.
Code
In the code snippet below, we use the var keyword to declare an array.
package mainimport "fmt"func main() {// array declarationvar marks = [5]int{50, 45, 30, 49, 38}// print on consolefmt.Println(marks)}
Explanation
In the code above:
- Line 3: We import the
fmtpackage.
- Line 7: Inside the
main()function, we use thevarkeyword to declare an arraymarksof typeintand length5. - Line 10: We output the
marksarray on the console.
2. The := operator
We can use the := operator to declare an array as follows:
arrayName := [length]dataType{elements}// orarrayName := [...]dataType{elements}
The properties are the same as those in the var keyword’s syntax.
Code
In the code snippet below, we use := to declare an array.
package mainimport "fmt"func main() {// array declarationmarks := [5]int{50, 45, 30, 49, 38}// print on consolefmt.Println(marks)}
Explanation
In the code above:
- Line 3: We import the
fmtpackage. - Line 7: Inside the
main()function, we use:=to declare an arraymarksof typeintand length5. - Line 10: We output the
marksarray on the console.