Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Declaring Arrays
course content

Course Content

Introduction to GoLang

Declaring ArraysDeclaring Arrays

Let's consider a scenario in which we need to store the names of ten students. To accomplish this, we have two options: we can create ten different variables of type string, or alternatively, we can utilize an array. An array is a fixed-size sequence of elements (values) of the same data type. In this particular case, we can create an array with a size of 10 and a data type of string to store the names.

To declare an array, you can use the following syntax:

For example, if we wish to declare an array named students with a size of 10 and a data type of string, we would write it like this:

Up to this point, we've only declared the array, so it doesn't contain any data and remains empty.

go

index.go

We can declare and initialize an array using the following syntax:

Note

Initialization refers to assigning an initial value to a variable or a data structure when it's declared. If an array is not initialized, it will take on the default values of its data type. For instance, an array of int data type will be filled with 0s, while an array of string data type will be filled with empty strings.

Using the syntax above, we can declare an array called students with a size of 4, containing four different names:

go

index.go

An array always has a fixed size, meaning that the size specified at the time of declaration remains constant for that array.

Another way to declare an array is by using the := operator, similar to how we use it for variables:

In the syntax above, the array is always both declared and initialized simultaneously. Consequently, we need to supply initial values for the array elements when using this approach.

If we construct the students array using the := operator, it will appear as follows:

go

index.go

question-icon

Complete the code for declaring and initializing an array called `vowels`:

Click or drag`n`drop items and fill in the blanks

Everything was clear?

Section 5. Chapter 1
some-alt