Skip to main content

Go Arrays

An array keeps several values of one type together under a single name. That saves you from creating a separate variable for every value.


Declare an Array

Go lets you declare an array either with the var keyword or with the := operator.

The syntax here uses var:

Example

Here the length of each array is written out: 3 for arr1 and 5 for arr2. One uses var, the other :=:

Prompt
Declare two arrays with defined size: one of strings with values, one of integers with values. Print both arrays.
Output: Go program and captured output

Example

Replace the length with ... and Go counts the values for you, so these two arrays end up with lengths 3 and 5:

Prompt
Declare two arrays with inferred length using the ... syntax. Print both arrays.
Output: Go program and captured output

Syntax

When you state the length yourself:

main.go
var array_name = [length]datatype{values}

Syntax

When Go works out the length for you:

main.go
var array_name = [...]datatype{values}

Access Elements of an Array

To read one element of an array, write its index number in square brackets.

Counting begins at 0, not 1, so [0] gives you the first element, [1] the second, and so on.

Example

Indexes 0 and 2 give the first and third values of prices:

Prompt
Declare an array of prices. Access the first and third elements by index.
Output: Go program and captured output

Change Elements of an Array

The same index notation works for writing: assign a new value to an index and that element is replaced.

Example

Assigning to prices[2] replaces the third value, 30, with 50:

Prompt
Declare an array, change the third element, then print the first and third elements.
Output: Go program and captured output

Array Initialization

Any array element you leave without a value is not really empty. Go fills it with the default value of its type, and the same goes for an array you never initialize at all.

Note: For int that value is 0; for string it is "".

Example

You can set only the positions you care about by writing index:value. Here index 1 gets 10 and index 2 gets 40, while the other three elements stay at 0:

Prompt
Declare an array of five integers where only some indexes are initialized. Print the array.
Output: Go program and captured output

Find the Length of an Array

To learn how many elements an array has, pass it to the len() function.