Array Literals and Parameters

This lesson explains array literals and handling arrays as parameters to functions in detail.

Array literals

When the values (or some of them) of the items are known beforehand, a simpler initialization exists using the { , ,} notation called array literals (or constructors) instead of initializing every item in the [ ]= way. Let’s see some variants.

1st variant

Specify explicitly the size n of the array with [n]. For example:

var arrAge = [5]int{18, 20, 15, 22, 16}

Here is another example:

var arr = [10]int{ 1, 2, 3 }

This is an array of 10 elements with the 1st three different from 0.

2nd variant

The […] notation, for example:

var arrLazy = [...]int{5, 6, 7, 8, 22}

... indicates the compiler has to count the number of items to obtain the length of the array. However, [...]int is not a type, so this is illegal:

var arrLazy [...]int = [...]int{5, 6, 7, 8, 22}

If the ... is omitted then a slice is created.

3rd variant

The index: value syntax can be followed. For example:

var arrKeyValue = [5]string{3: "Chris", 4: "Ron"}

Passing an array to a function

Passing big arrays to a function quickly eats up a lot of memory because arrays are copied when passing. There are 2 ways to prevent this:

  • Pass a pointer to the array.
  • Use a slice of the array (we’ll discuss slices in the next section).

The following example illustrates the first solution:

Get hands-on with 1200+ tech skills courses.