Course Content
Introduction to GoLang
Introduction to GoLang
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.
index
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 with0
s, while an array ofstring
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:
index
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:
index
students := [4] string { "Luna", "Max", "Ava", "Oliver" } fmt.Println(students) // Outputs [Luna Max Ava Oliver]
Thanks for your feedback!