LEARN GOLANG| Part-1

aditya goel
14 min readSep 24, 2022

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

  • Anatomy of GoLang program.
  • Variable declaration in GoLang.
  • Tools available in GoLang.
  • Numbers and Variables in GoLang.
  • Random Number in GoLang
  • Control Flows through If-Else in GoLang.
  • Control-Flow through Switch Case in GoLang.
  • Iteration / For-Loops in GoLang.
  • Usage of break keyword in GoLang.
  • Goto Statements.
  • Basic DataTypes in GoLang.
  • Custom DataTypes (Struct) in Go-Lang.
  • Example to showcase usage of struct in Go.
  • Usage of constructors in GoLang.

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 :- Showcase any simple program written in GoLang, with a variable being declared into it ?

Question :- Explain the variable declaration statement within GoLang :-

Answer:- This is crucial statement and have been broken down below with explanation :-

  • var → The first word in here of var is short-form for variable. It informs go that we are about to create a new variable right after the word var.
  • card → We then declare the name of the variable.This can be any name. Here, we are using the name as “card”. So we are making a new variable called card.
  • string → The word string right here is telling the go compiler that only a value of type string will ever be assigned to this variable.
  • “Ace of Spades” → On the other side of the equal sign, we create a new string. It contains a value Ace of Spades, and that gets assigned to the variable card right here.

Question :- Can you explain the difference between the “Statically Typed Language” and “Dynamically Typed Language” ?

Answer:- JavaScript, Ruby and Python are all examples of dynamically typed languages, whereas C++, java and Go are statically typed languages.

A dynamically typed language is one in which you and I, the developers, essentially do not care what values we are assigning to any given variable. So for example, I’m going to pop open my chrome console right here, which is going to allow me to just very quickly write out a little bit of JavaScript.

  • Here, we have assigned number variable being equals to numeral integer 123 and then immediately underneath that I’m going to say number equals “abcd” i.e. a string.
  • With JavaScript, the interpreter does not care if we define a variable and assign it an integer and then later on assign it a string, which is what we’re doing right here.

Question :- Is there any other way, that variable-declaration can be done ?

  • At line number-7 here, we are relying upon the go compiler, to just kind of figure out that card is supposed to contain a string.
  • It does that by reading in this colon equals operator right here. So, this is essentially telling go, hey, we want to make a variable card called card and you need to figure out what type of data is going to be assigned to it.

Question :- Can we assign some other value to the existing variables ?

If we are reassigning an existing variable, a new value, we do not have to use the colon equals anymore. So, for example, if we re-assign the value “Five of diamonds” to the variable card, we can do so by just using an equal operator.

Question :- What shall happen, if we assign the different value to the existing variable ?

  • Since, GoLang is statically-typed language, we can’t assign a different type of value to the existing variable.
  • Note above that, at line number 7, we already assigned string type of value to the variable card. At line number 8, we now assigned integer type of value to the variable card, but this shall throw error.

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:- 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 Control-Flow through If-Else 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 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:- Explain once more, how does If-Else 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:- Demonstrate the for loop in Go-Lang ?

Answer:- There are 2 famous ways of looping though the array in Go-Lang :-

Basic fundamental goes like this :-

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:- Explain once more FOR Loop iteration with GO program ?

Answer:- There are multiple ways to specify FOR loops in Go :-

Question:- Explain concept of Strings in GO program ?

Answer:- Strings are immutable in Go i.e. they can’t be changed once created :

Question :- Explain the basic go data-types ?

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:- 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 ?

Answer:-

  • 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.

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 :-

--

--

aditya goel

Software Engineer for Big Data distributed systems