Beginners guide to Go-Lang | Part1
In case you are landing here directly, it’s suggested that you go and read through this for fundamentals.
In this blog, we shall be looking at following concepts :-
- Anatomy of GO program.
- Tools available in GoLang.
- Numbers and Variables in Go.
- Conditional Operators in Go.
- Iteration / Loops in Go.
- Slices in Go.
- Maps in Go.
- Functions in Go.
- Call by Value in Go.
- Call by Reference in Go.
- Usage of Pointers in Go.
- Error Handling and Panic in Go.
- Usage of Defer keyword in Go.
- External http Call from Go.
- Usage of struct in Go.
- Demonstrating the usage of “new()” in Go.
- Concept of Constructors in Go.
- Demonstrating the Example of Object with constructors.
- Coding to Interfaces.
Question:- Explain the anatomy of a GO program ?
Answer:- Let’s take a look at the small Go program and break it down line by line.
- The first line is a comment. You can either use single-line comments, like this, or multi-line comments, which start with a forward slash and an asterisk and end with an asterisk and a forward slash, very much like C++ or Java.
- Line three is package main. Go code is organised in packages. This helps in big projects, allowing teams to work on parts of the system independently. The main package has a special meaning in Go and it will make your code compile for an executable and not the package.
- Line five is an import statement. Go is a very simple language, and by itself, does not have many built-in functions. Most of the code you’ll be using will be in packages. Go comes with a start library which contains many packages.
- In line six, we import the fmt package. The fmt package contains functions for formatted printing.
- In line nine we have function main. We define a function with the func keyword. The body of the function is enclosed in curly braces. The function main also has a special meaning in Go. It will be executed by the Go runtime when the program starts.
- The println function from the fmt package prints its argument in a new line. You need to prefix the function name println with the package it came from.
- Unlike C++ or Java, you don’t need to place a semicolon at the end of the line. The message printed out is a string. Strings in Go starts and end with double quotes.
- Go strings are Unicode, which means you don’t need special code to support non-English languages.
Question:- Explain the Tools of a GO program ?
Answer:- Let’s take a look at the following ToolSet provided by GO language. Go comes with a tool called Go. You use the Go tool for most everyday tasks such as building, testing, benchmarking, and starting third party packages and more :-
Compile and Run → In the above program, Behind-the-scenes, Go tool does following things :-
- To compile your program and then run it.
- By design, the Go compiler is fast, go run works quickly and enables fast development cycles. Let’s clear the screen.
Build → With above snapshot, we demonstrate, how do we build an executable that we can distribute.
- This is done with the go build command. Go build Welcome.go. And Enter. You created a file called welcome.
- On Windows, it will be welcome.exe. And if you run it, welcome, you will see the same output for our program. Let’s clear the screen again.
Help → The Go tool can execute several other commands. To see all of them, run go help. Let’s go over some of these commands.
- test → It will run the tests. Go has a built-in test suite. Test can also run benchmarks so you’ll be able to measure performance of your code.
- get → It is for installing third-party packages. If you need to connect to a database, pass file format such as yaml.
- fmt → It will format your code. Most editors run fmt upon save. This eliminates these long and boring discussions about code format. There are many other commands and with time, you’ll probably use more of them. Modern IDEs such as Visual Studio Code or Golang will run a lot of the Go tool commands for you.
Question:- Explain the Numbers and Assignments inside the GO program ?
Answer:- Let’s take a look at the following program to compute the Median with INTEGERS :-
- We declare two variables, x and y, of type int. And unlike C or Java, the type comes after the variable name. In Go, you have int8, int16, int32, int64, and the unsigned versions of all of them. The int type, without size, depends on the system you are using, and is the one you will usually use.
- If you don’t assign a value to a variable, Go will assign the zero value for this type. In this case, it will be zero value @ lines 9 and 10.
- In lines 12 and 13, we assign values to x and y.
- In line 15 and 16, we use fmt.Printf. The Printf function gets a template to print and then a value to fill this template. The %v verb will print a Go object and the %t verb will print its type.
- In line 18, we define mean and in line 19, we assign the value of x plus y divided by two. And in line 20, again we print the value of mean and its type.
- Since here, both x and y have type as integer, therefore the type of result is also integer. The result is 1, not 1.5 as expected. The reason is that integer division returns an integer.
Let’s take a look at the following program to compute the Median with FLOATING point numbers :-
- At line nine and change the variable x to float64. There are two kinds of floats in Go, float64 and float32.
- Go’s type system is very strict. It doesn’t allow to add integer to a float. Therefore, both the variables @ line 9 and 10, have been converted to float types.
- Automatic Type Inference → What’s nice about GO is that the compiler can infer the type of variables for you.
- If you declare a variable but don’t use it, Go will treat this as an error. This might be annoying, but it will protect you from a lot of bugs.
Question:- Explain how does Conditionals work with GO program ?
Answer:- There are two ways to specify conditions in Go : if and switch. Let’s start with if :-
- In line nine, I’m assigning 10 to the variable x. And then in line 8, I can ask if x is bigger than five. Unlike Java or C++, you don’t need parenthesis around the condition. And if you run it, go run if.go, we’ll see that x is big is being printed out.
- At line 11 if x is bigger than a hundred, it will print that it’s very big but this is going to be false, so we’ll go to the else section and print that x is not that big.
- You can use double ampersand for a logical and. So if x is bigger than five and x is smaller than 15, it will print out x is just right. When we run it here, we’ll see that the last statement is x is just right.
- In the same way that we used double ampersand for and, we can use double pipe for logical or. So we set it, if x is smaller than 20 or x is bigger than 30, we print it x is out of range.
- If can have an optional initialization statement as well unlike Java. At line 24, We assigned 11 to a and 20 to b, and then we asked, if fraction which is a divided by b, and then semicolon and then asking the condition, is fraction bigger than 0.5, it will print out that a is more than half of b.
Let’s now have a look at Switch Statement :-
- We start with an initialization statement. In our case it’s just the value of x. And then we list the cases here.
- In the last switch statement, we get x is small, that is coming from the default statement because, both of above cases have actually failed.
Question:- Explain FOR Loop iteration with GO program ?
Answer:- There are multiple ways to specify FOR loops in Go :-
Question:- Explain concept of Strings GO program ?
Answer:- Strings are immutable in Go i.e. they can’t be changed once created :
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:- 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:- Demonstrate the concept of Functions with GO program ?
- Functions in GO can very well return. multiple values too.
- Functions receive variables and also have return-types defined in definition itself :-
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 Value → When 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 Reference → However, 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:- 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.
Question:- Demonstrate the usage of error in GoLang ?
Answer:- Go functions can return more than one value. This is used extensively in Go to signal errors. Error is a built-in type that’s used throughout Go. The function that can error, will usually return the error value as the last value returned.
- Here we have an sqrt function, which calculates the square root of a number. But, unlike the one in the math standard library this one will return error on negative numbers.
- We can see from above method that, we return two values. One is float 64, which is the result, and the other one is of type error.
- At line #10, we are returning zero, because we have to return some value for the float, but also we are returning a new error.
- At line #13, we are returning the square root of n and nil. Nil is the value that Go uses to signal nothing. It is very much like null or none in other languages.
You are going to write a lot of : if err does not equal nil code. You might find this tedious, but I personally found it made my code much more robust, and forced me to think about every error.
Question:- Does GoLang also have PANIC and Should we use that ?
Answer:- Yes, Go also has something called panic, which is somewhat similar to exceptions in other languages. The use of panic is discouraged in Go and is considered an anti-pattern. The way to signal an error is to return it.
Question:- Explain the automatic memory management with GoLang ?
Answer:- Go has a garbage collector, which means you don’t have to deal with memory management. When you allocate an object and then stop using it, Go’s garbage collector will clear it up.
Question:- Whats the concept of Resource in GoLang ?
Answer:- Go have various kind of resources. For example :- Memory, Files, Sockets, Virtual-Machines and others. You’d like to make sure that these resources are closed when you’re done with them as well.
Question:- How do we free-up resources in GoLang ?
Answer:- To make sure a resource is closed, we basically use defer. Let’s see an example :-
- At line # 7, cleanup() is a function that will free your resource.
- At line #12, We use a defer code, to free this resource, but note that, first the worker code is executed and only then the the defer’s code is executed. Defer will be work even if you have an error or a panic in your code, making sure that your resources will be freed, in any case.
- What’s nice about defer is that you write it just after you acquire the resource. This way, you don’t forget to make sure it’s freed. Defer the code in reverse order.
Question:- Demonstrate an example of invoking external URL along with usage of defer, in GoLang ?
Answer:- Below method demonstrates that, a particular function can very well return multiple data from one single method :-
- At line #12, we are hitting to the external URL, using the http package. We are also catching the response and error from the same.
- At line #16, we are well using the defer keyword, by the help of which, we indicate that we need to close the ResponseBody, post the processing of this particular method is done.
- At line #17, we are getting the value of “Content-Type” and it’s an automatic type guessing here.
Question:- Demonstrate the usage of struct, in GoLang ?
Answer:- Below method demonstrates the creation of custom defined structure :-
At line #9, we have created an object of struct type : “Trade” with 4 attributes in it.
- At line #14 above, we have initialised an object of struct type : “Trade”.
- At line #18 above, it is yet another way of initialising an object of struct type : “Trade”.
- At line #25 above, note that, an empty object of struct type : “Trade” has been initialised. Therefore, when we print the same, all of it’s attributes have been initialised to the default values.
Question:- Demonstrate the concept of Constructors with GoLang ?
- If you’re coming from an object-oriented language, such as Python, Java, C++, and others, you are used to having a constructor or initializer method that is called when an object is created.
- In Go, you write a function, usually starting with New, that returns a new object. This New function usually returns the pointer to the created object, and optionally, an error value, If it’s possible there was an error creating the object.
- Here, we are validating the data. For example → If the symbol is empty, we return nil for no object and an error that the symbol can not be empty. We also check the volume, that it’s not negative and we check the price, that it’s not negative.
- Once we’ve validated the input, we create a pointer to a trade object, and at the end, we return the trade object, and nil, signifying no error.
Here, Interesting fact to note down is that, Go’s compiler doesn’t escape analysis and will allocate trade object on the heap. Let’s now use this method, in order to create the object.
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 series.