Go – Create Integer Array

In this tutorial, we will learn how to create an Integer array in Go: declare and initialize an Integer array. There are few methods based on whether we declare and initialize the array in one statement or separately.

To declare an integer array arrayName, with size arraySize, use the following syntax.

</>
Copy
var arrayName [arraySize]int

And to assign values for array elements, we can use array-index notation as shown below.

</>
Copy
arrayName[index] = someValue

In the following example, we will declare an integer array intArr of size 3, and then assign values to the elements of this integer array.

example.go

</>
Copy
package main

import "fmt"

func main() {
	var intArr [3]int
	intArr[0] = 10
	intArr[1] = 20
	intArr[2] = 30
	fmt.Println(intArr)
}

Output

[10 20 30]

To create Integer Array, which is to declare and initialize in a single line, we can use the syntax of array to declare and initialize in one line as shown in the following.

</>
Copy
arrayName := [arraySize] int {value1, value2}

where

  • arrayName is the variable name for this integer array.
  • arraySize is the number of elements we would like to store in this integer array.
  • int is the datatype of the items we store in this array.
  • value1, value2 and so on are the initial values we would like to initialize this array with.

In the following example, we will declare and initialize an integer array intArr of size 3 in a single line.

example.go

</>
Copy
package main

import "fmt"

func main() {
	intArr := [3]int{10, 20, 30}
	fmt.Println(intArr)
}

Output

[10 20 30]

Conclusion

In this Golang Tutorial, we learned how to create an integer array, with the help of example programs.