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
.
In Golang, we can use two methods to declare an array.
var
keywordWe 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.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)}
In the code above:
fmt
package.main()
function, we use the var
keyword to declare an array marks
of type int
and length 5
.marks
array on the console.:=
operatorWe 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.
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)}
In the code above:
fmt
package.main()
function, we use :=
to declare an array marks
of type int
and length 5
.marks
array on the console.