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.

A sample array

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}
// or
var 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 main
import "fmt"
func main() {
// array declaration
var marks = [5]int{50, 45, 30, 49, 38}
// print on console
fmt.Println(marks)
}

Explanation

In the code above:

  • Line 3: We import the fmt package.
  • Line 7: Inside the main() function, we use the var keyword to declare an array marks of type int and length 5.
  • Line 10: We output the marks array on the console.

2. The := operator

We can use the := operator to declare an array as follows:

arrayName := [length]dataType{elements}
// or
arrayName := [...]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 main
import "fmt"
func main() {
// array declaration
marks := [5]int{50, 45, 30, 49, 38}
// print on console
fmt.Println(marks)
}

Explanation

In the code above:

  • Line 3: We import the fmt package.
  • Line 7: Inside the main() function, we use := to declare an array marks of type int and length 5.
  • Line 10: We output the marks array on the console.

Free Resources