Today I Learned

A Hashrocket project

Using an array literal to specify length

Go forces you to specify the length of an array when creating or declaring an array. If you don’t declare the length then its not an array its a slice. The syntax for declaring the array looks like this:

// array of length 3
var numbers = [3]int{1, 2, 3}

When we use an array literal with the {} to declare the values of an array, the length declaration becomes redundant.

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

The above example, however shows the declaration of a slice not an array. To let the literal define the length of an array we can place the ... operator inside the [] square brackets.

var numbers = [...]int{1, 2, 3}

Now, we can add a fourth element to the array without also having to change the specified length.