Here are three ways to initialize an array in Go:
- Using an array literal
- Using ellipses
- 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.

Krunal Lathiya is a seasoned Computer Science expert with over eight years in the tech industry. He boasts deep knowledge in Data Science and Machine Learning. Versed in Python, JavaScript, PHP, R, and Golang. Skilled in frameworks like Angular and React and platforms such as Node.js. His expertise spans both front-end and back-end development. His proficiency in the Python language stands as a testament to his versatility and commitment to the craft.