A Beginners Guide to Go Programming

Akshay Bobade
7 min readJun 28, 2021

--

What is Go?

Go is an open-source programming language that makes it easy to build simple, reliable, and efficient software.it is a statically typed, compiled programming language designed at Google by Robert Griesemer, Rob Pike, and Ken Thompson. Go is syntactically similar to C, but with memory safety, garbage collection, structural typing, and CSP-style concurrency.

Why did Google create a new language?

Go was born out of frustration with existing Programming language and environments for systems programming. One had to choose either efficient compilation, efficient execution or ease of programming. All three were not available in the same Programming language.it forced googler’s to rethink and create compiled solution that allows for massive multithreading, concurrency, and performance under pressure. Their aim was to make Go is intended to be fast: it should take at most a few seconds to build a large executable on a single computer.

Advantages of Go:

  1. Golang is Fast- Go has a simple structure and syntax.The language is based on functions, so it is simple and fast to learn. It’s compiled so it provides faster feedback, shorter time to market, and saves time and money.
  2. Golang is concurrent- Concurrency is extremely important factor as it allows multiple processes running simultaneously. It has similar efficiency like c and C++ and can be done in easier manner using goroutines,garbage collection etc.
  3. Golang is cross-platform- it compiles well on many OS’s.
  4. garbage collector- Automatic memory management which can help to bust performance.

In this Article, you will learn:

The objective of this article is to show you how to write a program with Go. I will explain to you syntax and show some tricks you might not know about in Go. Following important topics will be covered.

  1. Installation of Go
  2. How to compile and run go program
  3. Packages in Go
  4. variable declaration and initialization
  5. Type of variable
  6. Type casting
  7. Loop
  8. conditinal statement
  9. defer statement
  10. Functions

1.Installation of GO:

for windows:

  1. Open the below url in browser and it will start downloading the installer and it will install Go to Program Files or Program Files (x86)
https://golang.org/dl/go1.16.5.windows-amd64.msi

2. Check the Go lang is installed or not using below command.

$ go version

for Unix:

  1. Run the following as root or through sudo. it will Extract the archive you downloaded into /usr/local, creating a Go tree in /usr/local/go.
rm -rf /usr/local/go && tar -C /usr/local -xzf go1.16.5.linux-amd64.tar.gz

2. Add /usr/local/go/bin to the PATH environment variable.

export PATH=$PATH:/usr/local/go/bin

Please note : Changes made to a profile file may not apply until the next time you log into your computer so its better if you add it in .profile.

Verify that you’ve installed Go by typing below command:

go version

2.How to compile and run go program:

Every Go Pragram has .go extention. You can build your Source code using go build command and it will build your source code and create a binary executable file. Then You can Run the binary file. Below I have build and executed sample sample.go file.

root@devopsguyvm:~/go/sample# ll
total 12
drwxr-xr-x 2 root root 4096 Jun 26 00:20 ./
drwxr-xr-x 3 root root 4096 Jun 26 00:20 ../
-rw-r--r-- 1 root root 99 Jun 26 00:19 sample.go
root@devopsguyvm:~/go/sample# go build -o bin sample.go
root@devopsguyvm:~/go/sample# ll
total 1908
drwxr-xr-x 2 root root 4096 Jun 26 00:22 ./
drwxr-xr-x 3 root root 4096 Jun 26 00:20 ../
-rwxr-xr-x 1 root root 1937631 Jun 26 00:22 bin*
-rw-r--r-- 1 root root 99 Jun 26 00:19 sample.go
root@devopsguyvm:~/go/sample# ./bin
Welcome to Beginners Guide to Go!!!!!!

As Go is compiled language like C,C++ that’s why it’s faster than interpreted languages like Node.JS and Python. Using go run command you can run the code without building its binary file (Golang builds the binary for run command but the binary is hidden) .


root@devopsguyvm:~/go/sample# ll
total 12
drwxr-xr-x 2 root root 4096 Jun 26 00:20 ./
drwxr-xr-x 3 root root 4096 Jun 26 00:20 ../
-rw-r--r-- 1 root root 99 Jun 26 00:19 sample.go
root@devopsguyvm:~/go/sample# go run sample.go
Welcome to Beginners Guide to Go!!!!!!

3.Packages in Go:

Packages are most Powerful part of Golang .The purpose of a package is to design and maintain a large number of programs by grouping related features together into single units so that they can be easily share and reuse.You can see the package in the code, it is the main package which is the root package for every Go program. And inside the main package, there is a main function which is also the first function to be run after executing a Go program.

Go language, every package is defined by a unique name and this name is known as import path. With the help of an import path, you can import packages in your program. e.g package main defined on first line on the below code.

root@devopsguyvm:~/go/sample# cat sample.go
package main
import "fmt"func main(){
fmt.Println("Welcome to Beginners Guide to Go!!!!!!")
}

4.Variable declaration and initialization:

As Golang is statically typed language hence you have to declare variable type when you declare any variable. It makes Golang faster as compiler dont need to define verify variable type at runtime.

There are three ways of declaring a variable.In first way you can just declare the variable and then initialized it but in this case type of variable must be specified at the time of declaration else go will throw an error. In second Place you can declare and initialized variable on the same line without manually specifying types but it uses the statement after the equals sign defines the type instead.In third approach if you want to exclude var keyword then you needs to have a colon (:) to declare the variable else compiler will throw an error.

You can declare multiple variables at once as well.

root@devopsguyvm:~/go/sample# cat sample.go
package main
import "fmt"func main(){
var a int //first type
a=2
var b= 3 //second type
c:=4 //third type
fmt.Println(a,b,c)
var d, 6 int = 1, 2}

5.Type of variable:

There are many types of variable in Go. in the article I have used some mostly used variable i.e. int,float,string,bool and map. You can find reference of it in below source code.

root@devopsguyvm:~/go/sample# cat sample.go
package main
import "fmt"func main(){
one := 3 // var one int
two := 3.00 // var two float
three := "devopsguy" // var three string
four := false // var four bool
five := info{Name:"Akshay",Age:24} // var five is map.
}

6. Type casting:

Some variable types can be easily converted to other variable types.e.g string to float, float to string etc. but for some conversion we need to extra go lang library to do the type conversion. e.g int to string, string to bool etc.

root@devopsguyvm:~/go/sample# cat sample.go
package main
import ("fmt"
"reflect"
)
func main(){
a := 3
b := float64(a)
fmt.Println(b,reflect.TypeOf(b))
}

root@devopsguyvm:~/go/sample# go run sample.go
3 float64

7.Loop:

In golang there is only one looping statement i.e.for loop

package mainimport ("fmt")
//You can define for loop by this way
i:=1
for i<=5{
fmt.Println("Go lang")
i++
}
//same way to define for loop
for i := 1; i<=5; i++ {
fmt.Println("Go lang")
}

8.Conditional statement:

In Go, there are control flow statements like other languages: if, else, switch, case.

//if else statement
test :=1
if test <= 5 {
println("Hi"}
} else {
println("Byeeee!")
}
//switch case statement in go
animal="lion"
switch animal {
case "cat":
animal = "N"
case "lion":
animal = "Y"
default:
animal = "X"
}

9. Defer statement:

Defer statement is a special statement in Go. You can call any functions after the defer statement. defer will keep it in a stack and they will be called after the caller function returns. In Go you can write multiple defer statements in the same program and they are executed in LIFO. it is mostly used to ensure that the files are closed when their need is over, or to close the channel, or to catch the panics in the program.

package main
import "fmt"

func xyz(a1 int) int {

result := a1
fmt.Println("Result: ", result)
return 0
}

func abc() {
fmt.Println("Hello!, Techies!")
}

func main() {
xyz(11)
defer xyz(12)
abc()
}
output<<
Result: 11
Hello!, Techies!
Result: 12

10. Functions in Go:

Go function has 4 parts.

  1. Name: Name should be in camelCase.
  2. Arguments: In Go lang function can take zero or more arguments. For two or more consecutive arguments with the same type, you need to define type at back of the last variable.
  3. Return Types: In Go lang a function can return zero or more value.If it is returning more than one value then you can to exclosed it in parathensis.
  4. Body: Where we defined actual logic.
package mainimport "fmt"// function to add number
func add (x int,y int) int{
var result int= x+y
return result
}
// function to return two values
func add1 (x int,y int) (int,int){
return x,y
}
func main(){
num3 := 3
num4 := 6
result1 := add(num3,num4)
fmt.Println(result1)
// in golang you can return two values from function
// function to return two values
result2,result3 := add1(num3,num4)
fmt.Println(result2,result3)
}

--

--

Akshay Bobade
Akshay Bobade

Written by Akshay Bobade

I have total 3 Plus years of experience as a Devops engineer and currently dealing with Cloud, Containers, Kubernates and Bigdata technologies.

No responses yet