Golang: Arrays

Golang: Arrays

Understanding the basics of Arrays in Golang

Introduction

In this fifth section of Golang, we will be understanding the basics of arrays. We will be covering some basic operations on arrays like declaration, initialization, modifications, and iterating over an array.

Declaring Arrays

Arrays are a type of data structure that allows us to store multiple items at continuous memory locations of the same type. In golang, we can create arrays similar to any variable but by adding a few bits and pieces like the [] square braces, length of the array, values, etc. In golang, we cannot resize the length once it is initialized.

To create a basic array in golang, we can use the following code:

package main

import "fmt"

func main() {
    var languages[4]string
    languages[0] = "Python"
    fmt.Println(languages)
}
$ go run basic.go
[Python   ]

Here, we have initialized a string array of size 4 and not initialized any values of the elements in the declaration. We later set the value of the 0th index or the first element in the array to a string and still rest of the elements are by default set to empty strings "". The point ot be noted here, is that the size of the array cannot be changed later nor you can leave the size empty while declaring an array in Golang.

We can even initialize elements at the time of declaring the array as follows:

lang_array := [4]string {"Python", "Go", "Javascript", "C++"}
fmt.Println(lang_array)
$ go run basic.go
[Python Go Javascript C++]

So, we use the walrus operator := to initialize an array with the values at the time of declaration.

Letting Compiler makeout the array length

We can even let the compiler decide the length of the array, using the ... syntax inside the brackets. This is limited by using the array literal that is by initializing values in the {} braces. So, all the elements need to be declared in the array.

cart := [...]string {"Bag", "Shirt", "Watch", "Book"}
fmt.Println(cart)
$ go run basic.go
[Bag Shirt Watch Book]

Access and Modify Elements

To access an element in the array, we can use the index of that element which starts from 0 as usual in programming.

marks := [6]int {85, 89, 75, 93, 98, 60}
fmt.Println(marks[1])
fmt.Println(marks[5])
fmt.Println(marks[3])
$ go run basic.go
89
60
93

We can now, access the element at a particular index in the array. Now, we will see how to modify or edit the elements which are already initialized.

name := [5]byte {'f','u','z','z','y'}
fmt.Printf("%s\n",name)
name[0] = 'b'
name[4] = 'z'
fmt.Printf("%s\n",name)
$ go run basic.go
fuzzy
buzzz

By accessing the index of the element we can set a appropriate value to the element in the array and thus we have modified the contents of the array.

Find Length of Array

To find the length of the Array, we have the len function. The len function takes in the array as the parameter and returns the size of the array(int).

code := [7]rune {'#', '5', 'g', 't', 'm', 'y', '6'}
fmt.Println("The length of the array is :", len(code))
$ go run basic.go
The length of the array is : 7

In the previous few section, we talked about letting the compiler make out the length of the array while declaring and initializing the array, we can use the len function to calculate the length of the array for further computation

cart := [...]string {"Bag", "Shirt", "Watch", "Book"}
fmt.Printf("There are %d items in your cart\n", len(cart))
$ go run basic.go
There are 4 items in your cart

We can now get the length of the arrays even with [...] syntax using the len function.

Iterate over an Array

We can move on to the most important aspect when it comes to arrays i.e. to iterate over each element. We can use various types of for loops like the three states for loops, range-based loop, or while loop.

Three statement for loop

We can use the three statement for loop, the initialization statement as to 0, condition to be the counter (i) should be less than the length of the array by using the len function and increment each time by one.

code := [7]rune {'#', '5', 'g', 't', 'm', 'y', '6'}

for i := 0; i<len(code); i++{
    fmt.Printf("%c\n",code[i])
}
$ go run basic.go
#
5
g
t
m
y
6

Thus, we can iterate over the array with three statements for loop in golang.

Using range-based loop

We can use the range keyword to iterate over the arrays in golang. The range keyword is used to iterate over the array by taking two variables i.e. the iterator and the copy of the element in the iterator. We don't have any use of the iterator so we say it as _, otherwise, it gives a warning/error of not using declared variables. So, we only require a copy of the element in this case, so say it as s or any other name you like.

cart := [...]string {"Bag", "Shirt", "Watch", "Book"}

for _, s := range cart{
    fmt.Println(s)
}
$ go run basic.go
Bag
Shirt
Watch
Book

Thus, using the range based for loops we were able to iterate over the array for each element without needing any check condition and incrementation of the counter/iterator.

That's it from this part. Reference for all the code examples and commands can be found in the 100 days of Golang GitHub repository.

Conclusion

So, from this part of the series, we were able to understand the baiscs of arrays in golang. We covered from declaration of arrays to iteration. Thank you for reading. If you have any questions or feedback, please let me know in the comments or on social handles. Happy Coding :)