How to Initialize an Array in Golang

Here are three ways to initialize an array in Go:

  1. Using an array literal
  2. Using ellipses
  3. Initialize special values

Method 1: Using an array literal

The easiest way to initialize an Array in Go is to use the “array literal”.

An array literal is a sequence of values enclosed in curly braces {} and separated by commas. When initializing an array, you need to specify the type and the size of the array.

Example

package main

import (
  "fmt"
)

func main() {
  // Initialize an array of integers
  var arr1 [5]int = [5]int{11, 21, 19, 46, 18}
  fmt.Println("Array 1:", arr1)

  // Initialize an array of strings with implicit size
  arr2 := [...]string{"bmw", "audi", "mercedez"}
  fmt.Println("Array 2:", arr2)

  // Initialize an array with default zero values
  var arr3 [3]float64
  fmt.Println("Array 3:", arr3)
}

Output

Array 1: [1 2 3 4 5]
Array 2: [apple banana cherry]
Array 3: [0 0 0]

Method 2: Using ellipses

You can use ellipses (…) during array initialization to let the compiler determine the array size based on the number of values you provide.

Example

package main

import "fmt"

func main() {
  numbers := [...]int{1, 2, 3, 4, 5}

  fmt.Println(numbers)
  fmt.Println(len(numbers))
}

Output

[1 2 3 4 5]
5

Method 3: Initialize specific values

You can initialize specific elements of an array at the time of declaration by providing index positions.

Example

package main

import "fmt"

func main() {
  numbers := [5]int{0: 19, 2: 21}

  fmt.Println(numbers)
}

Output

[19 0 21 0 0]

That’s it.