Learning Golang ? Start here !

Prabesh
9 min readApr 7, 2022

--

After playing with go for a while, i have decided that i will start to write some blog about go and some information which you need to know to get started on learning go lang. At least what i followed to knowing go to effectively start writing your own application or api.

First of all, let’s do a small theory on what is go and why go after all you would need to know why you choose to work with go and not with other programming language like python, java etc

What is Go ?

Go is a statically typed, compiled programming language which was created at Google around 2007–2009. Go syntax are some what inspired from C with whole lot more features like garbage collection, concurrency etc.

Why use Go ?

Programming is like juggling. You would need to know how to juggle between multiple programming language based on the work you are doing. Go was built by legends who has worked in the same industry for decades and have seen the issues with past and modern programming language. The main reason to choose Go over other language like python are:

  1. Has built-int garbage collectors which prevents memory leaks and proper memory management.
  2. Unlike C, C++ or even JAVA, sytanx of Go is very easy to read, write and understand. This was intentional. Creators of Go ( Ken thomson and team) wanted to make programming effecient but also want to keep it simple.
  3. One thing which fascinated me was Go does not use while loop, but instead for loop can be used to perform this task.
  4. Error handling is also another important factor which i like about go. Comparing to other programming language, there are need to handle errors with exceptions but error handling is done as part of go code itself and is easier to implement.
  5. Speed and Performance is another contributing factor. If you want your application to be very fast and give high performance then it is better to develop application in Go. As we know, running pre-built and compiled binary is faster than running through application directly from source code. Some more info on performance
  6. Concurreny and Channels is another feature that makes go first class choice for creating concurrent application. Go uses something called goroutines and channe to help create concurrent applications.
  7. Source code formatting code formatting is also another feature which is very neat. Gone are the days where you go about formatting your code for better readability.
  8. Go is opionated programming language. It follows good type system and It also throws error when unused variable and libraries exists in application.
  9. Easy packaging and compilation of application based on target OS and Architecture.

Prerequisite

To be honest, there are not any pre-requisite of learning go. You can use go as your first programming language and still be okay with it. If you have some prior programming experience with language like C, Java, Python then it will be easier to understand.

When to use Go ?

There are always tradeoff in any language you choose and go is no different. It sure has some disadvantages, it is time consuming compared to writing code in python, it is still young, there are not much frameworks built. It is up to developer to acknolwdge these limitations and know what language is better for your application.

Go is better suited for creating backend applications / apis where performance, memory footprint, processing time, concurrency matters.

Dissecting a simple hello world go app

First of all, all go codes are created in a file called *.go. In go, there should be an entrypoint of the application and is generally defined in file called main.go but you can name it any filename. main.go is the main entrypoint into the application.

Let’s look at a sample Hello world code written in go

package mainimport "fmt"func main() {
fmt.Println("Hello world")
}

Let’s have a closer look at the code

package main : Go has an idomatic approach where program execution starts. It first looks for main function inside main package to start the execution. Go application must have a main package which acts as an entry point to your application. This directive means that this file is a main file for the go application.

import "fmt" : This step is importing fmt package which consists of methods to stdout information using Println or Printf and more.

func main() {} : This step tells we are creating a function named main. As discussed each go should have a main package and this main function is the entrypoint of that app. Go looks for main function as an entrypoint function.This is similar to creating main function while using JAVA applications.

fmt.Println("Hello world") : This step tells that we want to use Println method from fmt package. Println formats the input with the default formats for its operands and writes to standard output. Spaces are always added between operands and a newline is appended.

Now, we know write a simple go application, let’s try to run it. You can run go programs direcly like this

% go run main.go
Hello world

or, you can compile the code into a binary executable and run from it. This method is much faster. This will create an executable main and you can execute it like how you run other executable.

% go build main.go
% ./main

You can use go online editor to code and run you code Here

Revision

Go is very good for creating backend application for web servers and for creating really fast utilities. Go is young but with that is promised right now, we know for sure that Go is here to stay.

Let’s move on to next

Commenting in Go

In Go comments are written as // for single line comment and /* */ for multi line comment.

// Single line comment/*
This is a
Multi line comment
*/

Tips: It is good to comment your functions so that it can be view as part of function when you hover mouse over it. eg: if you write function like this and hover mouse over the function usage in part of code, it will show the function documentation there making it easy to know what that function what and it’s usage.

// When you comment over function like this, it can be seen when mouse is hovered over
// the function making it easy to read what function does
func adder() {
}

Above will be shown like this

Variables and Constants

Go is staticaly typed programming language hence variable type must be explicitly declared. When creating a varible there are two step, first one is declaring variable ( declare what type ) and second is initializing ( initialize value). You can declare variable like this

var [variable_name] [variable type]

eg:

var myName string
var age int

If the value to the variable is given at declaration then Go will automatically infer the variable type. For example if you declare variable like this var age = 2 then it auto detects it is a variable of type int or if you declare variable like this var name = "prabesh" then it auto detects it is a variable of type string which is neat.

You can also assign multiple variable at once like this

var value, status = "12", true

Variable can be declared to be used later in programs without assigning values to them. When a valiable.

When a variable is declared without assigning value then by default they will hold empty value i.e. if you declare int variable then by default its value will be 0 and if you delare a string variable then it will hold empty string not nil.

Variable can be declared and initialized using short hand version as well using := operation. This mean you are declaring and initializing a variable i.e. var age int = 2 can be written as age := 2. This makes things a lot easy.

Constants can be declared using const operator. Unlike variable, their value cannot be changed through out the program. A constant is declared like this

const pi float32 = 3.1415

Integer, Float, Strings and Rune

Integer in go can be declared by adding int type to the variable declaration like this var age int = 24

Floating point number can be declared by adding either float32 or float64 type in the variable declaration like this var pi float32 = 3.14 or var pi float64 = 3.1415. float32 uses 32 bits of memory and stores value in single floating point format where as float64 uses 64 bits in memory and stores values in double floating point format.

Similar to other language strings are the collection of character. eg "This is a string" is a string with multiple character and "a" is also a string with single character ( including the double quotes).

If you represent "a" like this 'a' ( notice the single quote), then it is called a rune where that character can be represented in Unicode code points.

package mainimport (
"fmt"
)
func main() {
var age int = 22 // Integer
var pi float32 = 3.14 // Floating point number
var double_float float64 = 3.141562 // Double float

fmt.Println(age)
fmt.Println(pi)
fmt.Println(double_float)
rune := 'a'
string_with_single_char := "a"
string_with_multiple_char := "Prabesh"

// This prints unicode code point
fmt.Println(rune)

// This prints out character
fmt.Println(string_with_single_char)

// This prints out string with multiple char
fmt.Println(string_with_multiple_char)
}

You can run and see the output here

Operations

There are various operations that we can do in programming i.e add, subtract, divide, multiple, calculate remainder etc. Let’s see how to do these. This is similar to other programming language.

package mainimport (
"fmt"
"math"
)
func main() {
fmt.Println("Addition", 1+2)
fmt.Println("Subtraction", 4-3)
fmt.Println("Multiple", 3*2)
fmt.Println("Division", 22/7) // This will give output in integer as it is integer operation.
fmt.Println("Division", 22.0/7) // For floating point operations js8ut add ".0" at end

fmt.Println("Exponential", math.Pow(20.0, 3))
fmt.Println("Reminder", 3%2)

// Boolean operations
fmt.Println("Greater than", 2 > 1)
fmt.Println("Greater than", 1 > 2)
fmt.Println("less than", 1 < 2)
fmt.Println("Greater or quivalent", 2 >= 1)
fmt.Println(4.0 == 4)
}

You can run the code here

Array, Slice and Maps

Similar to other programming language collections of data types can be done in various ways. They are described below one by one

Array

Array can be declared in go like this [name_of_array] := [length_of_array][array_type]{values} ( notice the curly braces). An array can have values with same data type. An example can be seen below

package mainimport (
"fmt"
)
func main() {
students := [3]string{"prabesh","pradip","asmita"}
fmt.Println(students)
}

Array can be defined without initializing before like variables and added later using the index like this array_name[index]. eg

package mainimport (
"fmt"
)
func main() {
movies := [3]string{} // Defined array of type string

// Adding values later to the array using the index
movies[0] = "50 Shades of Grey"
movies[1] = "X-men"
movies[2] = "Pokemon"

// Accessing individual element
fmt.Println(movies[2])

// Accessing whole array
fmt.Println(movies)
}

If no value is added in the arry the it will take the default value i.e if you declare array on int with 3 length and added value to first and not on remaining two then they will hold default value. Default values are

int = 0 
float = 0.0
string = ""

length of array can be accessed using built-in len function.

You can run the code here

You can also create multi-dimensional array as well like this

rectangle_coordinates := [2][2]int{}

Slice

Slices are used when you are not sure about the size of the array of when the size of array is not known. Creating slice is similar to creating array, you just do not specify the length.

You can declare a slice like this

surnames := []string{}

and append to that slice using append function

surnames = append(surnames, "Thapa")
surnames = append(surnames, "Silwal")
surnames = append(surnames, "Adhikari", "Tamang") // can do this also

example

package mainimport (
"fmt"
)
func main() {
// Slice = variable length array
surnames := []string{} // Declaring slices

surnames = append(surnames, "Thapa")
surnames = append(surnames, "Silwal")
surnames = append(surnames, "Adhikari", "Tamang") // Can append multiple data at once.

fmt.Println(surnames)
}

You can also create a slice of fixed length using make method. eg:

package mainimport (
"fmt"
)
func main() {
// Slice = variable length array
surnames := []string{} // Declaring slices

surnames = append(surnames, "Thapa")
surnames = append(surnames, "Silwal")
surnames = append(surnames, "Adhikari", "Tamang") // Can append multiple data at once.

fmt.Println(surnames)
movies := make([]string, 4) // Creating a slice with a default value of 4
movies[0] = "He-man"
movies[1] = "Ant man"
movies[2] = "Iron man"
movies[3] = "Hulk"
fmt.Println(movies)
}

You can run the code here

Slice supports usage of slicing operation : with syntax `slice_name[low:high]

Map

Maps are similar to dicts in other programming languages. You can define a map using hte map keyword like this map[type_of_key]type_of_value eg

student := map[string]string{
"name": "prabesh",
"address": "11 nsw str",
"phn_no": "1246322562",
}

You can just declare map only as well without any values

ages := map[string]int{}

Addition is similar to adding an item in an array but this time you use the key instead of the index number.

ages["kabita"] = 68
ages["pradip"] = 21
ages["prabesh"] = 20

Deletion is done using delete method and passing map and its keyword

delete(ages, "prabesh") // delete entry from map

example

package mainimport (
"fmt"
)
func main() {
// map[type_of_key]type_of_value
birthday := map[string]string{
"name": "prabesh",
"address": "11 bond str",
"phn_no": "0414032050",
}
fmt.Println(birthday)
ages := map[string]int{} // defining map without any pre-values
ages["prabesh"] = 26
ages["kabita"] = 68
ages["pradip"] = 21
ages["prabesh"] = 20
delete(ages, "prabesh") // delete entry from mapfmt.Println(ages)
}

You can run the code here.

--

--

Prabesh

Senior Site Reliability Engineer & Backend Engineer | Docker Captain 🐳 | Auth0 Ambassador @Okta | https://www.linkedin.com/in/prabeshthapa