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

Зміст курсу

Introduction to GoLang

Introduction to GoLang

1. Getting Started
2. Data Types
3. Control Structures
4. Functions
5. Arrays and Slices
6. Intro to Structs & Maps

Declaring 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

copy
1
fmt.Println(students) // Outputs [ ] which represents an empty array

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

copy
12
var students = [4] string { "Luna", "Max", "Ava", "Oliver" } fmt.Println(students) // Outputs [Luna Max Ava Oliver]

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

copy
12
students := [4] string { "Luna", "Max", "Ava", "Oliver" } fmt.Println(students) // Outputs [Luna Max Ava Oliver]
question-icon

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

Натисніть або перетягніть елементи та заповніть пропуски

Все було зрозуміло?

Секція 5. Розділ 1
We're sorry to hear that something went wrong. What happened?
some-alt