Go-Lang Hands-On| Part-3
In case you are landing here directly, it’s suggested that you go and read through this for fundamentals.

In this blog post, we are going to look at following topics :-
- Memory Management with Go-Lang.
- Variable Addressing Scheme.
- Pointer Notations.
- Arrays in Go-Lang.
- Slices in Go-Lang.
- Unordered Map in Go-Lang.
- Making Map an ordered Map.
- Custom DataTypes.
- Control Flows.
- Break Loop flows.
- Goto Statements.
- Functions in GoLang.
- Reading a File from Local Directory.
- Generating an output File from Local Directory.
- Scrapping data from Internet / Website.
- Parsing the text data into JSON.
Question:- How a GO application is being run ?
Answer:- When you run a Go application with the GO run command, you’re depending on the Go runtime that’s installed on your computer.
Question:- Is the GO runtime included with build ?
Answer:- When you compile and build a binary GO application, the runtime is included. Either way, your application depends on the runtime which operates in the background in dedicated threads.
Question:- How is the memory managed with GO-lang ?
Answer:- Like other managed languages, such as Java and C#, you don’t have to explicitly allocate or de-allocate memory in your code; it’s all managed for you in the background.
Question:- How do we initialise the complex types with GO-lang ?
Answer:- There are two built-in functions here, that we should be aware of :
- new() → With this function, memory is allocated, but it doesn’t initialise memory. When you allocate an object using the new() function, you’ll get back a memory address indicating the location of the complex data-type(e.g. map), but the data-type object itself has zeroed memory storage. The implication of this Zeroed Memory Storage is that : If you try to add a key-value pair to the map, it’ll cause an error.

- make() → With this function, memory is both allocated as well as initialised too. You’ll get back that memory address, just like you do with new(), but the storage is non-zero and is ready to accept values.

Question:- Can you demonstrate the usage of new() built-in functions ?
Answer:- Let’s take a look at this bit of code :-
- The first line declares a map object and says that the keys are strings and the associated values are integers. And I’m declaring that with the new() function.
- On the next line, I try to add a key value pair. And then I try to output the contents of the map, but I’m not going to get to that third line of code. Instead, the app will crash and I’ll see a panic error. It’s telling me that, I’m dealing with a map with zero memory storage.
- There’s just no place to put the data, because memory is zeroed with new() function. And so there’s a panic and the application crashes.

Question:- Can you demonstrate the usage of make() built-in function ?
Answer:- Let’s take a look at this bit of code :-
- Here, we have wrapped our declaration in the make() function which does allocates as well initialise the memory too.
- In this version of the code, I’m once again saying that it’s a map object that contains strings as keys and int as values, but this time, I initialise with make(), and now when I try to add an entry, it’ll succeed. And when I output it, I get this output.
- So, whenever you use these complex objects, it’s critical that you wrap the initialisation in the make() function, if your intent is to immediately add data to the object.

Question:- Can you demonstrate the usage of arrays with help of make() built-in function ?
Answer:- Let’s take a look at this bit of code :-

- Note that, we have declared a Slice at line #8 with the help of make function.
- Also note that, the initial capacity of the array has been declared as 5.
- At line #16, we are appending more element at the end.
Question:- How is memory deallocated with Go-Lang ?
Answer:- Memory is de-allocated automatically by the garbage collector that’s built into the Go runtime.
- The garbage collector runs in the background and each time it kicks in, it looks for objects that are out of scope OR set to nil, so it can clean out the memory and return that memory to your memory pool.
- The garbage collector was completely rebuilt in Go 1.5 for very low latency to reduce the pauses that happen when you’re running Go applications. And now, the process for de-allocating memory goes by so quickly that you’re very unlikely to notice it, even on slower computers.
Question:- Does GO support usage of pointers ?
Answer:- Yes, GO supports the use of pointers. These are variables that store the memory address of another variable.
Question:- Can you demonstrate the usage of pointer ?
Answer:-
- Demo #1 → Here, *int indicates that, thisVar is a pointer and not value. And if I don’t assign anything, that means that, variable will be nil; it doesn’t contain anything.

- Demo #2 → Here, we are printing the *thisVar, which indicates that, thisVar is a pointer and not value. This time, it throws the RuntimeError indicating the InvalidMemoryAddress.

Question:- Can you demonstrate, how a particular variable can refer to the address of another variable ?

- Here, variable “thisParticularInVar” is valued at 75.
- The Pointer-Variable “thisPointerVar” is pointing to the address of variable thisParticularInVar.
- The notation “&thisParticularInVar” is pointing to the address of variable thisParticularInVar.
- The notation “*thisPointerVar” is referring to the actual value being stored at address stored in thisPointerVar.
Question:- If we try to manipulate the value of a variable through it’s pointer, then whether the actual value of the variable shall also be changed ?

- Notice that, at line #8, we specifically want the type of the variable to be inferred. Here, we want that GO-compiler should be auto-inferring the type of 75.
- Note that, At line #14, we modified the value of the variable ‘thisParticularInVar’ through it’s pointer variable.
- The change made through the pointer variable is very well reflecting in the original variable too.
Question:- Can you demonstrate the usage of Arrays in GoLang ?

- We have declared an Array of Strings at line #8. This is an Array of 4 Strings have been initialised.
- At Line #9, the array of 5 integer values have been explicitly initialised and in subsequent lines, we are assigning values to each array index. Note that, we are just using the “=” symbol i.e. assignment operator, because we don’t need to infer the type anymore.
- Also, we have demonstrated the usage of “len” method, to showcase the length of the array here. Recall that, this method “len” comes from a special package named builtin. The Go compiler assumes that the builtin package is always imported.
Question:- Given the fact that, we have defined the array of fixed size, what would happen, if we add value to the index, which has not been declared
Answer:- We shall land into OutOfBounds situation, as we try to add the value to the Index, which doesn’t exists at all. This is one of the shortcoming of the fixed size Array.

Question:- Can we perform the Sorting on the Arrays ?
Answer:- No again, this is yet another issue with the Arrays. We can’t perform the sorting operation on the Arrays.

Question:- What’s the alternative ? How can we make it possible that, we can add unlimited entries to the Array ?
Answer:- This is possible with SLICE. Here is an example for the same :-

- Note that, at line #14, we are trying to add more entries tot he Array earlier declared. And we can add infinite elements, there is no constraint of size here.
- Also observe that, at line #16, we are performing the sorting operation of the Array Slice.
Question:- Demonstrate the Unordered Map with Go-Lang ?
Answer:- In Go-Lang, we have an unordered collection of elements called Map :-

- Note that, we are using make() function at line #8, in order to initialise the Map.
- At line #8, we have defined the Map with both <K,V> as of string type.
- At line #16, we are also performing the delete operation basis of key.
Question:- Demonstrate how can we iterate through the Unordered Map in Go-Lang ?
Answer:- While, we iterate through Map, order is not guaranteed. Here is how we can iterate through the Map :-

Question:- How do we print the entries (K,V) pair from the MAP in ordered way ?
Answer:- We can first take the keys from the map, sort them and then basis of keys, we can print the entries from the Map :-

Note here that, at Line #15, we are making use of the Slices. This is one special variety of Unbounded Array, which can grow as much as we want.
Question:- Let’s demonstrate the Custom DataTypes in Go-Lang ?
Answer:- We can declare custom data-types in Go using “struct” keyword. We can use a struct to group and store multiple values.

- At line #17 to 19, each value of a struct is technically known as a field.
- At line #10, we have printed the entire custom object and it’s printing the name of the attribute as well as it’s corresponding value.
- At line #12, we are referring the attributes through object access.
Question:- Let’s demonstrate the Control-Flows in Go-Lang ?
Answer:- We can use If-Else control flows like as follows :-

- Notice that, we can’t use angle-brackets for putting the conditions for check.
- Also note that, the curly braces have to be on the same line. From Java, we can even write the starting curly braces in the next line as well.

Question:- Let’s demonstrate the Random Number in Go-Lang ?
Answer:-
- We can use a package called math/Rand and another package the time package that we’ve seen before. From the rand package, I’m calling the seed function and passing in the current time in Unix format.
- Then I’m using a function called Intn and passing in a ceiling of seven, and then adding one, and this will give me a number between one and seven. Each time I run the application, I’ll get possibly a different number.
- And it all depends on the millisecond of the current time on my computer. It is possible to see the same number over and over again. But that’s just coincidence.

Question:- Let’s demonstrate the Switch Loop in Go-Lang ?
Answer:- We do have switch case where decision is to be taken against the variable. Whatever it’s value is, basis of the same, the particular case is executed.

Question:- Let’s demonstrate the fallThrough scenario of Switch Loop in Go-Lang ?
Answer:- In case, we wanted to skip through the particular use-case, we can add the fallthrough keyword for that particular case.

Note here that, though the value of the variable “thisVar” is 1 and it should had come to the case 1, but all the cases are having fallthrough clause and that’s why, all cases are skipped and therefore control logic comes to the last case.
Also, remember that, all the cases can’t be skipped :-

Question:- Let’s demonstrate the for loop in Go-Lang ?
Answer:- There are 2 famous ways of looping though the array in Go-Lang :-

Question:- Let’s demonstrate the for loop in Go-Lang ?
Answer:- There are 2 famous ways of looping though the array in Go-Lang :-

Question:- Let’s now demonstrate the break keyword in Go-Lang ?
Answer:- The break and continue keywords works exactly the same way, as they work in JAVA/C++ languages.
- break → It breaks the flow of the code and ends the loop.
- continue → It just restarts the flow of the code from the beginning.

Question:- Let’s now demonstrate the GOTO labels in Go-Lang ?
Answer:- The goto labels in Go-Lang can be used to directly bunzy jump to a particular statement, but be careful while using the same, as it can very soon create spaghetti code. Here, the same is demonstrated :-

Question:- Let’s now demonstrate usage of functions in Go-Lang ?
Answer:- We shall be defining the function, which would perform ADD operation on two integer type numbers :-

Question:- How can we define the method, which can take unknown number of variables in request and perform some action in function in Go-Lang ?
Answer:- We shall be defining the method in below fashion :-
- This method can receive infinite values in input.
- This method would return ONE value of int type.

Remember that, in case we want, even we can just skip the index very well by using _ (underscore) character. In below case, we shall not have any need to even make use of the Index :-

Question:- How can we define the method, which can return multiple values?
Answer:- We shall be defining the method in below fashion, which would be returning the multiple values :-

Question:- How can we define the functions as method of custom types?
Answer:-
- Here In Go-Lang, we can attach functions to your custom types. They’re then referred to as methods.
- In a more completely Object Oriented language such as Java, you’d say that each method is a member of a class whereas In Go, a method is a member of a type.

Question:- Does methods work on CallByReference OR CallByValue?

Answer:- Within the function at line #21, I’m reassigning the value of the sound field.
- So what do we think is going to happen? Will the dog bark three times, or nine times? And the answer is that it only barks three times.
- That’s because, when you pass the dog object in as the receiver, a copy is made of it, it’s not a reference. If you want it to be a reference, you can use pointers. But within the function, this is a brand new copy of the object, so when I modify the sound field, I’m not modifying the version that was created in the main function.
Question:- Let’s demonstrate now process of generating an output file in Go-Lang ?

- Here @ line #13, we are specifying the name of the file, that we are planning to generate.
- Here @ line #16, we are suggesting to generate a file with data being stored in the variable “content”.
- In the output section below, it’s evident that a output file has been generated well.
- Here @ line #19, keyword “defer” is very important, as it shall wait for everything, untill this line executes.
Question:- Let’s demonstrate now process of reading a given input file in Go-Lang ?

- Here @ line #14, we are specifying the name of the file, from which we are planning to read the data.
- Here @ line #20, note that, data being read from the file is always in BYTES format and we need to convert the same to string format, to display the same in human readable format.
Question:- Let’s demonstrate now process of scrapping some data from Internet in Go-Lang ?

- Here @ line #12, we are using the http.Get call in order to receive the data from aforementioned URL.
- Here @ line #17, we are reading the response thus received in the “resp” variable.
Question:- Let’s now parse the aforesaid JSON-data into some meaningful information ?

Here @ line #47, we created our own custom data-type to convert the each data to the structure type.
That’s all in this section. If you liked reading this blog, kindly do press on clap button multiple times, to indicate your appreciation. We would see you in next series.
References :-
- https://adityagoel123.medium.com/in-conversation-with-go-langs-datatypes-part2-fa0b7ca98725
- https://adityagoel123.medium.com/in-conversation-with-go-lang-part1-57753b03072e
- https://adityagoel123.medium.com/installing-verifying-go-in-vs-at-mac-ef15a909d8fa
- https://github.com/adityagoel123/GoLangBasics
- https://golang.org/pkg/runtime
- https://talks.golang.org/2015/go-gc.pdf
- http://services.explorecalifornia.org/json/tours.php
- https://go101.org/article/memory-block.html
- https://go.dev/tour/flowcontrol/1