Arrays

An array is a common data structure that exists in any programming language. In Go, an array is a collection of values with the same data type, and a pre-defined size.

Here is how to declare an array in Go:

var myarray [3]int

The preceding array is of type int and of size 3.

We can then initialize the array like this:

myarray = [3]int{1,2,3}

Or, we can do this:

//As per the array declaration, it has only 3 items of type intmyarray[0] = 1 //value at index 0myarray[1] = 2 //value at index 1myarray[2] = 3 //value at index 2

Alternatively, similarly to other variables, we can declare and initialize the array on the same line, like this:

var myarray = [3]int{1,2,3}

Or, if we are declaring and initializing the array inside a function, we ...

Get Hands-On Full Stack Development with Go now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.