To use arrays in our programs, we must first declare and name them. In Go, there are a variety of ways in which we can declare an array. In the next few exercises, we will explore methods of array creation.

When we declare a variable in Go, the compiler:

  • Finds space in memory for that variable
  • Associates the variable with a name

Using arrays makes the compiler’s job a little more complicated. When we declare a single variable, the compiler needs to find enough space for one of that data type. When we declare an array, the compiler is going to have to find enough space for several of a data type.

To make this process simple, declaring an array in Go requires that we provide the number of elements. Once declared, we cannot change this number without declaring a new array. The compiler finds enough space for the array’s type, multiplied by the number of elements.

We can create arrays with or without an initial set of elements. We use an array without initial elements when the rest of our program will create the array’s content. To create an array without an initial set of elements we use the following syntax:

var playerScores [4]int fmt.Println(playerScores) // [0 0 0 0]

This syntax creates an empty array of integer values with space for 4 elements. We could create an array like this and later fill it with values from user input.

While empty arrays are great for storing data we can’t predict, sometimes we already know what we want in our array! In the next exercise, we’ll introduce a way to create an array filled with particular values.

First, let’s practice creating an empty array.



Begin by creating an empty array of strings, playerNames with space for 5 elements


Next, print the content of the array you just created. What do you expect to see?

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?