Go – Declare and Initialize an Array in One Line

We can declare and initialize an array in one line in Go programming.

The syntax to declare and initialize an array arrayName of size arraySize in which elements of type arrayDataType are stored is

arrayName := [arraySize] arrayDataType {value1, value2}

The initial values are given as comma separated values enclosed in curly braces as shown in the code above.

The number of initial values must be less than or equal to the array size specified.

Examples

In the following program, we declare and initialize an array arr of size 4 and type int. The initial values for this array are {1, 4, 9, 16}.

example.go

package main

import "fmt"

func main() {
	arr := [4]int{1, 4, 9, 16}
	fmt.Println(arr)
}

Output

[1 4 9 16]

Now, let us provide initial values less than the specified array size.

example.go

package main

import "fmt"

func main() {
	arr := [4]int{1, 4, 9}
	fmt.Println(arr)
}

Output

[1 4 9 0]

If the initial values are less in number than the array size, then the default values of the specified datatype would be assigned for the rest of the values.

ADVERTISEMENT

Conclusion

In this Golang Tutorial, we learned how to declare and initialize an array in single line in Go programming, with the help of example programs.