Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

golang
communitycreator

How to declare an array in Golang

Shubham Singh Kshatriya

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}
Syntax using var

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)
}
Array declaration using the var keyword

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}
Syntax using :=

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)
}
Array declaration using :=

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.

RELATED TAGS

golang
communitycreator

CONTRIBUTOR

Shubham Singh Kshatriya
RELATED COURSES

View all Courses

Keep Exploring