LEARN GOLANG| Part-2

aditya goel
11 min readSep 25, 2022

--

In this blog, we shall be looking at following concepts :-

  • Concept of Arrays in GoLang.
  • Slices in GoLang.
  • Maps in GoLang.
  • Making Map an ordered Map.
  • Functions in GoLang.
  • Functions that takes-in input unknown number of values.
  • Functions that returns multiple values.
  • Call by Value in GoLang.
  • Call by Reference in GoLang.
  • Usage of Pointers for plain values in GoLang.
  • Usage of Pointers for Objects in GoLang.
  • Demonstrate an example of Objects with constructors.
  • Coding to Interfaces.

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:- Explain concept of Slices with GO program ?

Answer:- Slices are built on top of Arrays. Slices are powerful way of dealing with Array based Operations in Go :-

  • At line #26, We are iterating over the elements in the slice, you can use the conditional for loop. We start with zero, up to the length of the loons, and then i++, print the loon.
  • At line #32, as demonstrated, we also have a range keyword.
  • At line #38, If you want both the index and the value, we can use range with a double value context on the left side. So here in line 38 I have both i and name, and then I can print that the name is at a certain position.
  • If you want just the values, we have to use the underscore, as in line 43, because unused variables in Go are a compilation error.

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:- Explain concept of Maps with GO program ?

Answer:- Maps are well supported in Go, where we can house <K,V> pairs of varied types :-

Example:- Demonstrate counting of words along with their frequency using GO program ?

Question :- How do we declare any function in the GoLang ?

Question:- Demonstrate the concept of Functions with GO program ?

Answer:-

  • Functions in GO can very well return multiple values too.
  • Functions receive variables and also have return-types defined in definition itself :-

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:- Demonstrate the value passing to Functions with GO program ?

Very Important Concepts→ At line # 21, we have defined a function : double(val) → We see that the original value hasn’t changed.

  • Call by ValueWhen Go passes an integer to a function, Go passes it by value which means, Go will create a copy of this integer and pass it to the function. Any changes to the integer inside the function won’t affect the original value.
  • Call by ReferenceHowever, when Go passes a slice or a map to a function, it passes it by reference. This means that inside the function body, you’re working with the exact same object that was passed and any changes to the slice you make inside the function stay after the function is over.

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:- Demonstrate the usage of Pointers for Objects, in GO ?

Answer:- Here below code-piece :-

  • At line #21, the variable “p” houses the address of an object (which is of type “Point”).
  • At line #15, the address of object, is being received by the variable “p”.
  • At line #22, also note that, “Move()” is a method which is being invoked through a reference variable. Here, the methods are not combined together with the struct class.

Question:- How can you make method work, with plain values in GO ?

Answer:- You can do this by using pointers. If you’re coming from C or C++, the word pointer might be associated with obscure code and crashes. Don’t worry, Go’s pointers are not like C or C++. They are much safer.

Demonstration:- Let’s showcase an example of nested objects with their methods exposed :-

Solution:- Here, we are showcasing the Square shape with nested object of Point in it :-

Step #1.) Let’s first create a Point struct :-

Step #2.) Let’s now write up a method Move, to showcase the movement of Point :-

Step #3.) Let’s now create a Square struct :-

Step #4.) Let’s now write up methods : Move & Area, to showcase the movement of Square AND calculate the area of Square :-

Step #5.) Let’s now create constructor for our struct Square:-

Step #6.) Let’s test the functionality by invoking the afore-written methods :-

Question:- Demonstrate the concept of Interfaces with GoLang ?

Usecase:- You have some shapes defined, like square and circle. Both the square and the circle, we find an area method. Now we’d like to write the function that receives a slice of shapes and return the sum of the areas.

Concept) What’s an Interface ?

Answer:- An interface is a collection of methods, and each type, it implements all the methods in the interface. Interfaces are a very useful abstraction and you’ll see them a lot. For example, the io.reader and io.Writer from the I/O package, define something you can read from and something you can write to. With these interfaces, you can use the same code to read from files, socket, compressed files, hash signatures, and more.

Demo Step #1.) Let’s first mention the packages that we shall be importing :-

Demo Step #2.) Next let’s create an Interface named “Shape” :-

Demo Step #3.) Next let’s create an struct (i.e. custom structure / POJO) with name “Square” :-

Demo Step #4.) Next let’s create a method “Area()” in order to compute the area of Square :-

Demo Step #5.) Next let’s create an another struct (i.e. custom structure / POJO) with name “Circle” :-

Demo Step 6.) Next let’s create a method “Area()” in order to compute the area of Circle :-

Demo Step 7.) Next let’s create the method “sumAreas()” in order to compute the sum of areas of all shapes received :-

Note that, we are receiving the slice of Shapes inside this method and in turn, we return the sum total of areas of all shapes.

Demo Step 8.) Next let’s test run this method :-

Demo Step 9.) Here is output :-

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 part of this series with Hands-On with Redis-Cluster.

References :-

--

--