Introduction
This blog is a documentation of my learning of the Go language, I'm more active in Cloud Native and DevOps space and the Go power this ecosystem and widely used tools for container orchestration like Kubernetes, tools used for containerization like Docker, and Infrastructure as Code like Terraform and the list goes on Why Go is widely used in DevOps and Cloud Native space and there's even more to it and has even more use cases of Go and Why Go was created? is the question to ask and here's an extensive read for What is Go?.
Install Go on your local machine
- It's pretty simple installing Go for Windows and macOS, and not so simple for Linux-based machines, let's install Go using CLI and here we Go!!
download the Go file from Go download package and it'll prompt you for where to download you can choose any empty folder, I'd prefer to go with the "Downloads" folder and complete the instructions provided on the website using the terminal
ctrl + alt + t
and next ctrl + alt + t will open the terminal now run this command
ls
andll a.k.a ls -l
,ll
: long list command it's like detailed info provided to the user
- unzip the file in the Downloads folder using
cmd:
tar -xzvf go1.18.2.linux-amd64.tar.gz
were using "tar" because it's a ".tar" file type and -xzvf "-" is for option flags like concatenating the single letter option into a stringxzvf
: extract zip being verbose and file now run "ls"
- Run
ll go
andll go/bin
and.go/usr/bin/
, you can see the command and help guide
- now we want to move the file to the "users" file location cause it allows us to run it from anywhere on our pc using cmd:
sudo mv go /usr/local/
, sudo is like "run as administrator" or it is used when any command requires elevated permissions, cmd to know more:man sudo
orwhatis sudo
- now let's check our user folder
cmd:
ll /usr/local/
, you can now spot the go folder
- get back to the "home" directory and run cmd:
go
, and the output will be the same as ./go/bin/go
- check it with cmd's "which go" and "go version" and Congrats you've made it ๐๐, You're good to go as a Gopher now, let's rock!!
- If you run into any problems check this video on Install Go
Let's start with writing some Go code
What happens from creating a "Go" program to executing it?
It starts with creating a module, A module is where the packages and packages consist of our .go files/source code so why do I need a module? I already have a package that has my .go file.
In Go I need not write the functions which have already been written by other folks, I just need to import the package from that particular module ok but what's the role module here, what does it do?
Modules are the ones that keep track of our dependencies. My program is dependent on the package which is distributed by some other module and that other package's module has dependent on some other module.
In my program hello.go, I imported a package rsc.io/quote and refer to pic how modules keep track of it using the command:
go list -m -u all
and I did it by initializing a module using the command go mod init / here I've used example/hello , initializing a module is very important
next are packages where my source code resides. here are the steps to create a program in short:
- We initialize a module before writing our program
- and then packages
- Then I start writing the program, in this case, it's hello.go
to import the whole module, use the command: go get x where x = GitHub repo link or directory in your PC or any, where the codebase is being hosted
But here the execution takes place the other way first, we run the program using cmd:
go run hello.go
code which is in the package main of our code file and our package is in the module since we have a dependency package next step would be looking into our go.mod fileSo it started from the code then running the package in order to run it went to the go.mod file to get the dependent package.
Basically, we are importing the functions which are in another package of the other module
Package the way Go code is organized and the module is a collection of packages
If you know the function you want to use you can use it right away Go takes care of handling the dependencies
Variables in Go
๐ What are Variables? We access data and store data from it , they are like an alias to the data in memory, data can be anything like numbers, words, or symbols, what we see is a form of data of different types.
๐ All Data Types and Default Types string, int, bool, byte, rune, uint32, float64, complex128 are the default native types -->The individual data types have even more memory types to them.
--> They are used only in necessary conditions like if you want your program performance to be at its utmost --> Check out this blog on boot.dev it's explained even better like when to use these types, and know more about Default data types in Go
๐ Creating/ Declaring Variables --> The variables can be created without storing any data in them using the "var" keyword --> Variable consists of a Type, a Name, and Data --> They can be created as Single, Compound, or as a block depending on how you use them
๐ Single Creation --> when variables are created using the var keyword and without having any data stored in it or a value to it. --> then the variable's default value will get assigned to them accordingly by their type.
--> Default values for the types or to the unassigned variables
- for string it is ""
- int it is 0
- bool it is false
- others it is nil
- When data is stored in a variable we call it an Assignment, like a value assigned to the variable
- No need for the var keyword for created variables, we can access them directly by their name
- ๐ Compound and Block Creation --> Compound method is used for creating multiple variables on a single line --> Used at a local level it means inside a function --> Block creation is done for a set of variables used mostly at a global level
๐ Short Hand Notation -->
:=
colon and equal to is used a.k. Create & Assign a variable and value, we do not even have to declare the type --> It is often used by every Go programmer, I mean why would I use var every time I create a variable and assign a value to it.--> Note that when this is used you have to assign a value to it, you cannot leave the value empty and Go it strictly typed so you will get an error -->Though it is smart enough to assign the type to the variable by looking at the value provided.
--> Create & Assign works only inside the function --> var keyword shines here, declaring variables everywhere --> We can reassign the value to the variables, --> Value is provided as a copy, not as a reference to the original value hence it does not have any effect on it.
Functions in Go
๐ What are functions? --> They are basic building blocks for a program --> In Go, we deal with packages, it is packages that consist of the Go code --> It's even better to say that package is a collection of multiple functions, let's save packages and modules for another thread
--> Functions are like the isolated workspace, knowing where lies where makes it easier to test, debug, read, write, and modify --> Functions take data as input and return data as output --> Taking input and returning the output is completely optional --> Let's take the simple greet function as an example
- Let's see how a function works in Go
- --> You can call this from anywhere you want, it can be from the main function or inside of some other function like this one in the picture, the output is still the same --> here we as the caller provided the input params for the functions like sum(9, 10)
- --> Functions in Go can return multiple values --> we created a function that returns two numbers of our choice --> we performed the sum function on it and ran the program --> as you see on the bottom left of the image the sum is 23 --> as you see the output is two ints
- ๐ Ignoring the output values --> Yes we can ignore the values using the "_" (underscore)
- with "_"
- without "_"
- If we want to use both the return values, then that is all about returning values
๐ Named returns --> Until now we returned output values without naming them is called a "naked" return --> we can also name our return values, take close look at the output values
Named return
- Naked return
--> We use named return values in long / larger functions with fewer parameters, I mean input arguments --> We use it in order to be more descriptive and our code to be well documented
๐ Implicit
--> it only works when return types are named
๐ Early return --> To return early from a function we use guard clauses --> It's simple if conditionals use them in a linear way --> To return from a function when a given condition is met --> Know more about it at this blog of Guard clauses
๐ Explicit return --> it is used for overwriting the return values this works when we name the return values --> else we can just return it as naked values
if-else statements and switch-case in Go
๐ What are if and else? --> They are known as conditionals --> A program executes line by line, conditionals are a way to control the flow of it. --> Conditions are used to execute the program the way we want
๐ if-else Condition --> Go is heavily borrowed from the C language but unlike C the conditions in Go don't have to be in parentheses --> Conditions are squared off to bool values(True or False) so the programs executed accordingly
- ๐ if...else if Condition --> It's simple, for multiple conditions we use else if --> Depending upon the number of conditions we can use as many else if we want
- ๐ Logical Operators for conditions and if-else usage with functions --> We use logical operators to satisfy one condition for multiple values and will evaluate to the bool type
- ๐ Statement Initialization in conditions --> We create and assign a variable to a value, and then we put a condition and then perform the logic check --> code executes if the conditions evaluated to true
๐ Switch-case --> if-else is used to execute the code based on the logic check on the given condition --> But switch executes the code based on the value check by using different cases
-->It performs execution when there's a match with the value/condition with the condition provided when we declared the switch statement and the condition provided in the case statement --> cases are like multiple if...else if but there's a catch, we'll to it very soon
- ๐ Conditional Cases --> Here we create and assign a variable to a value, and the conditions go inside the case statements --> We use logical operators and the evaluate to bool type but values are being compared in the given conditions here, that's the catch
- ๐ Case Lists --> executing the code for a case for multiple arguments in the condition at the same time --> Like switch statement has values like an array of numbers --> what we do here we can perform a certain task for different numbers using them as chunks
- ๐ Fallthrough --> By now I hope I was able to give you a good idea about how if-else statements works --> Switch method has a hack to execute the next case irrespective of the condition using the "fallthrough" keyword --> "fallthrough" forces the execution of the next case
Looping in Go
๐ What are Loops in general? --> Like we are logging in to our account, it can be any account --> You enter your username and password, click on the login button --> And you've entered the wrong password, the message pops up --> We do know that there's a "forgot password" option
--> But we were sure that we know it, maybe in a hurry we tend to do it again and again --> After a while, we exhaust all the attempts, and the "try again after some time" message pops up --> So what happened here, maybe there's a loop with a condition
--> Which contains no. of possible attempts that can be made in one go or a continuous loop that breaks after a certain condition is met. --> Hope, I was able to give you a quick brief about loops Let's get into how looping is done in Go.
๐ Basic Loop in Go --> As from the above example, you can observe the fact that we need loops to repeat actions --> To perform a task or iterate over items in a collection --> In Go, the "for" keyword is used for looping just the one keyword for all types --> After creating and assigning the variable for iteration, the program executes until the condition evaluates to true --> Only after that, the loop gets to the post statement and perform the increment/ decrement operation, or something more
--> Loops statements are separated by semicolons";" same as in C but no parentheses here if you observe --> The statements start with initialization which in this case is " i := 0 " and then the condition " i < 5 ", and i++ is the post statement
--> After creating and assigning the variable for iteration, the program executes until the condition evaluates to true --> Only after that, the loop gets to the post statement and perform the increment/ decrement operation, or something more
- ๐ for: while loop --> There is no while loop in Go, but we can use the while functionality using the "for" keyword with a given condition
๐ for: Infinite loop --> Loops which continue forever, we just have to use the "for" keyword and write the program that's it --> If we wish to break the infinite loop, we have to provide a condition within the loop and use the "break" keyword if the condition is met.
- ๐ for loop using the "Continue" --> To skip the current loop we use the "continue" --> It returns from the current iteration and continues from the next iteration if you folks remember about Guard clauses, Continue keyword is the best way to use in them
Thank You so much for reading it till the end, I hope this got you started with Go, and If found this helpful give me a shoutout on Twitter and feel free to connect with me on Twitter at Kiran_Satya_Raj and
Happy Learning in Public