Go: Basics

Go: Basics

Go fundamentals

ยท

13 min read

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 and ll a.k.a ls -l, ll: long list command it's like detailed info provided to the user

image.png

  • 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 string xzvf: extract zip being verbose and file now run "ls"

image.png

image.png

  • Run ll go and ll go/bin and .go/usr/bin/, you can see the command and help guide

image.png

image.png

image.png

  • 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 or whatis sudo

image.png

  • now let's check our user folder cmd: ll /usr/local/, you can now spot the go folder

image.png

  • get back to the "home" directory and run cmd: go, and the output will be the same as ./go/bin/go

image.png

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

image.png

  • 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

image.png

image.png

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

  1. We initialize a module before writing our program
  2. and then packages
  3. 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 file

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

  1. for string it is ""
  2. int it is 0
  3. bool it is false
  4. 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

image.png

  • ๐Ÿ“Œ 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

image.png

  • ๐Ÿ“Œ 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.

image.png

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

image.png

  • Let's see how a function works in Go

image.png

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

image.png

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

image.png

  • ๐Ÿ“Œ Ignoring the output values --> Yes we can ignore the values using the "_" (underscore)
  • with "_"

image.png

  • without "_"

image.png

  • If we want to use both the return values, then that is all about returning values

image.png

  • ๐Ÿ“Œ 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

image.png

  • Naked return

image.png

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

image.png

  • ๐Ÿ“Œ 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

image.png

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

image.png

image.png

  • ๐Ÿ“Œ 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

image.png

  • ๐Ÿ“Œ 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

image.png

image.png

  • ๐Ÿ“Œ 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

image.png

  • ๐Ÿ“Œ 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

image.png

  • ๐Ÿ“Œ 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

image.png

  • ๐Ÿ“Œ 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

image.png

  • ๐Ÿ“Œ 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

image.png

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

image.png

  • ๐Ÿ“Œ 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

image.png

๐Ÿ“Œ 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.

image.png

image.png

  • ๐Ÿ“Œ 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

image.png

image.png

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

ย