Golang Tutorial

Golang, popularly known as Go, is an open-source programming language designed at Google by Rob Pike, Robert Griesemer, and Ken Thompson in 2007. This language offers all kinds of features that developers like, such as structural typing, garbage collection, and more. It’s also been a high-paying programming language for the last few years due to its extensive use in various applications and platforms. 

This Golang Tutorial walks you through all the essential concepts of Golang, from the absolute basics to all the way up to advanced features. Our Go tutorial is suited for both beginners and experienced developers. With the help of this, you can learn and polish your skills in Golang.

In this Golang Tutorial, I will be discussing the following topics:

What is Golang?

Go commonly known as Golang, is a programming language. It is a freeware programming language originally developed at Google. It allows parallel programming, i.e., multiple programs are executed concurrently. The Syntax of the Go Programming Language is identical to C Programming Syntax. It supports garbage collection and contains many built-in functions. The program execution procedure used in GoLang is similar to that of C Programming.

Why Golang?

The main purpose of developing the Golang programming language is to eliminate the problems faced by existing programming languages. Golang allows using different programming paradigms. It offers the same performance as C, is much easier to maintain than Java, and so on. 

The language began rising almost as soon as it was released back in 2009. It quickly started drifting from below position toward the top positions around the world.

According to the latest reports, there is considerable demand for Golang and popularity among developers, and it also falls under the list of top learning programming languages for the year 2021.

Golang Features

The best features of Go are as follows:

  • The time required for compiling a Go Program is very low.

  • The Go Programming Language is Platform Independent.

  • It supports Type Embedding and Interfaces.

  • It has inbuilt library functions.

  • Go Programs are simple and brief.

Inclined to build a profession as GO Developer? Then here is the blog post on, explore GO Training

Go Download and Installation

Download and install Golang with the simple steps described below.

Step 1: Go to https://golang.org/dl/ and download the binary release of your operating system.

Download and Installation

Step 2: Double-click on the installer and click on Next to set up the wizard.

Installation

Step 3: Click on the Next option to accept the end-user license agreement.

Accept the End - User License Agreement

Step 4: Select the installation folder and click on Next.

Installation - Destination Folder

Step 5: Click on install to finish the installation.

Installation Finish

Step 6: Once the installation is done, you can verify it by opening the terminal by typing

$ go version

This will display the version of Go installed.

Create your first Go program - Hello World

Go files are created using the .go extension, and Go programs are run using the syntax:

go run <filename>

Create a file trial. go and add the below code into it
package main
import ("fmt")

func main() {
fmt.Println("Hello World")
}

Now run the file trial. go to see the result

go run trial.go

Output

Hello World

Related Article: Golang Interview Questions

Basic concepts of Golang Programming Language

Every Go Program Contains the following Parts:

  • Declaration of Packages

  • Package Importing

  • Functions

  • Variables

  • Expression and Statements

  • Comments

MindMajix Youtube Channel

Let us see a sample Go Program.

package Mind  // Declaration of Package

import "go1"  // Importing Package

func main()  // main() function

{

Go1.println(" Hello World")

In the above program, we have the following statements:

  1. In the first Statement, we have defined a package called “mind”, and our program should be stored in that Package.

  2. In the second statement, we have imported a package called “go1”, and the files present in that package are included in our program.

  3. In the next line, we have declared the main() function, and from there, program execution begins.

  4. In the main() function, we have a println() function that makes the “Hello World” message displayed on the screen.

After writing the program, we have to execute the program. Let us see the procedure for executing a program.

Go Program Execution

For Executing a Go Program, we have to follow the below steps:

Step 1: Write the Go Program in a Text Editor.

Step 2: Save the program with “.go” as the program file extension.

Step 3: Go to Command Prompt.

Step 4: In the command prompt, we have to open the directory to save our Program.

Step 5: After opening the directory, we have to open our file and click enter to compile our code.

Step 6: If no errors are present in our code, then our program is executed, and the following output is displayed:

"Hello World"

Data types are used to declare variables and functions. Data types indicate how much space should be allocated to a data member, like variables, functions, etc. In the Go Programming language, Data types are classified into different types:

  • Boolean Types - The Boolean Type variables will take only two values: 1) True and 2) False.

  • Numeric Types - Data types like Integer, float come under this type. The Numeric type variables store only numerical values. 

  • String - A String data type takes a collection of string values. The values once stored in the string variable cannot be deleted.

  • Derived Types - In Go Programming language, we have different derived types, they are: i) Arrays ii) Pointers iii) Unions iv) Structures v) Interfaces vi) Functions

A Variable is defined as a name mentioned to a memory location that the program can control. In the Go programming language, every variable will have a data type, which indicates how much memory is required for storing that variable.

Variable Declaration

A Variable Declaration indicates to the compiler how much memory should be created for storing that variable. The Syntax for Variable Declaration is as follows:

Var Variable_list1 optional_data_type;

In the above statement, the optional_data_type contains Go data types like int, string, float, boolean, etc. The variable_list1 comprises the list of variables.

Example:

var a, b, c float;
var e, f, g int;

Variable Initialisation

At the time of declaring a variable, it can be initialized with certain values. According to the values initialized to the variable, the compiler evaluates the data type of that variable. Variables are initialized through the assignment operator “=”. 

The syntax for a variable initialization is as follows:

Variable = value;

Example:

i=7, k=3;

Static Type Declaration in Go

The Static type variable declaration gives the compiler that only one variable exists with the given name and types such that the compiler can continue further compilation excluding other details of the variable.

Example:

package main

import "fmt"

func main() {
  var x float64
  a = 12.0
  fmt.Println(x)
  fmt.Printf("a is of type %Tn", a)
}

Output:

a is of type float64

Dynamic Type Declaration/Type Inference in Go

In the Dynamic Type Declaration of a variable, the compiler has to evaluate the type of the variable according to the value initialized to it.

Example:

package mind

import "go1"

func main() {

Var z int = 30;

i := 75;

go1.println(z);
go1.println(i);
go1.println(" z data type is %Tn", z);
go1.println(" i data type is %Tn", i);
}

Output:

30
75
z data type is int
i data type is int

Scope of Variables

The scope of variables tells us where we can access a variable and where we cannot access a variable. Based on the scope, the variables are classified into two types: they are:

  • Local Variables - These variables are declared inside a block or a function. They are accessed by the statements which exist in that module or function.

  • Global Variables - Generally, global variables are declared at the topmost part of the program. so, they can be accessed by any statement present in that program

Constants are defined as permanent values such that programs may not change them at the time of program execution. While declaring constants, we should use the “const” keyword.

Example:

Package mind

import "go1"

func main() {

const side int = 12
var ar int

ar = side*side

go1.println(" Area of square is : %d ", ar)
}

Output:

Area of square is: 144 

An operator Symbolically tells the compiler to do particular arithmetic or logical operation. The Go Programming language supports the following operators:

  • Arithmetic operators

  • Logical operators

  • Assignment operators

  • Bitwise operators

  • Relational operators

  • Miscellaneous operators

Arithmetic operators

In the Go programming language, we have several arithmetic operators. They are as follows: Let us imagine that we have two integer variables like C=10, and d=50.

Operator Description Example
+The addition operator is used to add two operands. C+D=60
-Subtraction is used to subtract the second operand from the first operand.D-C=40

*The multiplication operator is used to multiply two operands. C*D=500

/The division operator is used to divide the numerator with the denominator.D/C= 5

%The Modulus operator is applied to return the remainder after the division operation.D%C=0
++The increment operator is applied to increase the value of a specific variable.C++ = 11

--The decrement operator is applied to decrease the value of a specific variable. D-- = 49

Logical Operators

The Go Programming language supports different logical operators who are as follows:

  • AND Operator - The logical AND operator is indicated by the “&&” symbol. When both operands contain non-zero values, then the result becomes true.

  • OR Operator - The logical OR Operator is indicated by the “||” symbol. When any one of the two operands is true, then the result will be true.

  • NOT Operator - The NOT Operator is indicated by the “!” symbol. It will complement the given input.

Assignment Operators

The Go programming language supports different assignment operators; they are as follows:

Operator Example
The “=” operator is used to assign the values present in the left operand to the right operand.C+D=E
The “+=” operator is used to add the right operand to the left operand, and then the result is assigned to the left operand.C+=E is equal to C=C+E
The “-=” operator is used to subtract the right operand from the left operand, and then the result is stored in the left operandC-=E is equal to C=C-E
The “*=” Operator is used to multiply the left operand with the left operand, and then the result is assigned to the left operator.C*=E is equal to C=C*E
Bitwise operators

The working of Logical operators is the same as Logical Operators. The truth tables for Bitwise operators are as follows:

CDC & DC | DC ^ D
01010011000101110101
Relational Operators

Relational operators are used to evaluate the relationship between the two operands. The different relational operators are as follows:

Operator Description
==The equal to the operator is used to check whether the left operand’s value is equal to the value of the right operand or not. If they are equal, then the result will be true; otherwise, it will be false. 
!=The “not equal to” operator is used to check whether the left operand’s value is equal to the value of the right operand or not. If they are not equal, then the result will be true; otherwise, it will be false.

Other relational operators are Greater than(>), Lesser than(<), Greater Than or equal to(>=), and Lesser than or equal to(<=).

Miscellaneous operators

The Go Programming Language Supports two Miscellaneous operators, which are 

Operator Description
&The “&” operator is used to store the address of a particular variable.
*The “*” operator is used to refer to a pointer variable.

Intermediate concepts of Golang Programming Language

1. Conditional Statements

The conditional statements are also called decision-making statements. In Decision-making programs, the statements are executed depending upon the condition specified. If the condition is true, one statement is executed. Otherwise, another statement is executed. In the Go Programming language, we have different conditional statements are as follows:

  • If Statement

 syntax of “If” statement is :

if(condition){

Statement1;

}

Statement2;

If the condition present in the “if” block is true in the above code, then the statement1 is executed; otherwise, statement2 is executed.
  • If-else Statement

The syntax of the If-else statement is as follows:

if(condition){

Statement1;

else

Statement2;

}

If the condition present in the “if” block is true in the above code, then the statement1 is executed; otherwise, statement2 is executed.

Example

package mind

import "go1"

func main() {

Var c=15 int

if(c<10) {

go1.println(" value of c is less than 10")       

else

go1.println("value of c is greater than 10")

}

}

  • Nested If statement

The syntax of the "Nested If" statement is as follows:

If(Condition-1) {

statement1

if(Condition-2) {

Statement2

}

}

In the above code, one if "statement" is placed inside another if statement. When condition-1 is true, statement1 is executed, and condition-2 is checked. If condition-2 is true, then statement-2 is also executed.

  • Switch Statement

The switch statement tests the variable by supplying different values. The syntax of the switch statement is as follows:

switch(expression)

{

Case-1

Statement

break;

Case-2

Statement

break;

Case-3

Statement

break;

}
  • Select Statement

Select Statement is identical to switch statement; the only difference is case refers to the channel communications.

Loop or Iterative Statements

The Loop or iterative statement enables the programmer to execute the same statement multiple times. In Go Programming Language, we have different loop statements; they are as follows:

  • For loop

The for loop executes a series of statements repeatedly. The syntax of for loop is as follows:

for( variable initialisation; condition checking; Increment/Decrement){

Statement1;

}

Example

package mind

import "go1"

func main() {

var c int

for (c=0; c<=10;c++)

{

go1.println(c);

}

}
  • Nested Loops

In Go Programming, nested loops provide the facility to run multiple loops inside another loop.

2. Strings

In Go Programming Language, strings are also known as slices. Strings are defined as collections of bytes. Strings can be created as follows:

var  =  "Welcome to you"

Manipulation Functions of String

In Go Programming, we have the following Manipulation functions:

  • Len(str) - This manipulation function is used to determine the length of a string.

  • Concatenate - This manipulation function is used to join or merge two strings.

3. Maps

Golang provides another important data type named Maps which maps unique keys to values. A key is an object that performs data retrieval of a value at a later date. Given a key and value, you can store a value in a map object. After storing the value, you can retrieve it using its key.

Example:

package main

import "fmt"

func main() {
  var countryCapitalMap map[string]string
  /* create a map*/
  countryCapitalMap = make(map[string]string)
 
  /* insert key-value pairs in the map*/
  countryCapitalMap["Bangladesh"] = "Dhaka"
  countryCapitalMap["Brazil"] = "Brasilia"
  countryCapitalMap["Greece"] = "Athens"
  countryCapitalMap["Austria"] = "Vienna"
 
  /* print map using keys*/
  for country := range countryCapitalMap {
      fmt.Println("Capital of",country,"is",countryCapitalMap[country])
  }
 
  /* test if entry is present in the map or not*/
  capital, ok := countryCapitalMap["India"]
 
  /* if ok is true, entry is present otherwise entry is absent*/
  if(ok){
      fmt.Println("Capital of India is", capital) 
  } else {
      fmt.Println("Capital of India is not present")
  }
}

4. Arrays

The array is a data structure that stores a fixed size of elements in sequential order. An array stores the elements which have the same data type. The array comprises contiguous memory locations. 

Array Declaration

In Go Programming, we can declare the array as follows;

var variable_name1 [size] data_type

Example:

var A[10] int

The above statement says that an array named “A” stores ten integer elements. The above array is a single or one-dimensional array.

Array Initialisation

In Go Programming an array can be initialized as follows:

Var A = [10] int {225, 475,355, 155, 635, 985, 555, 765, 895, 1015}

The elements of an array are accessed through their indexes. 

Example:

Int a= A[5]

The above statement says that the fifth element of the “A” array, is stored in the integer variable “a”.

The Go Programming Language Supports multidimensional arrays. In a multidimensional array, we will have multiple indexes.

5. Functions

A function is a self-contained program or a module in the program. It contains certain statements to do a specific task. The syntax of the function is as follows:

func function_name1 ( [list of parameters] ) [ return_type]

{

function_body

}

In the above code, we have:

  • func: with this keyword, the function declaration begins.

  • function_name1: This is the real name of the function. The name of the function depends on the operation it performs. 

  • Parameters list: The parameters act as input to the function. It will perform the operations on the given parameters.

  • Return_type: The return type specifies the data type of the values the function returns.

Function Calling

A program calls the function to do a particular task. After doing that task, the function will return the result through the return keyword.

1. Parameter Passing Mechanism

In Go Programming, we can pass the parameters from the calling function to the called function. The parameters present in the calling function are called Actual Parameters and the parameters present in the called function are called Formal Parameters. There are two ways of Parameter Passing; they are:

  • Call-by-value

In this method, the values of the actual parameters are passed to the formal parameters. The changes done to the formal parameters are not reflected in the actual parameters.

  • Call-by-Reference

In this method, the addresses of actual parameters are passed to the formal parameters. The changes done to the formal parameters are reflected in the actual parameters.

2. Recursion Function

The function which calls itself is called a recursive function. An example of a recursive function is as follows:

package mind

import " go1"

func fib1( a int) int {

if(a<=1) {

return 1

}

return fib1(a-1)+fib1(a-2)
}

func main() {

Var c int =3

go1.printf(" Fibonacci series is %d " fib1(c))
}

3. Pointers

The pointer is a variable that stores the address of another variable. The pointer variables can be declared as follows:

var var1_name *var1_type

In the above statement, var1_name is the name of the pointer variable, and var1_type is the data type of the pointer variable. The asterisk symbol indicates that the declared variable is a pointer variable. 

Example:

Var d *int

We have declared an integer pointer variable.

As we have said that a pointer variable stores the address of another variable, Now let us see how it will store the address of another variable.

Var c int = 25 

We have declared an integer variable “c.”

Var e *int

We have declared an integer pointer variable “e.”

e = &c

By using the “&” symbol, we have stored the address of the variable “c” into the pointer variable “e”.

Note: The data type of the pointer variable and the data type of the variable of which the address is stored in that pointer variable should be the same.

4. Structures

Structures are another data type that exists in Go Programming. They are used to declare a record in the program. To declare a structure, we should use struct and type statements. The struct statement acts as a data type for structures. An example of a structure is as follows:

type student struct {

id int

name string

percentage float64

rank int

}

In the above code, a structure called “student” is declared. The data members of that structure are 1) id 2) string 3) percentage 4) rank. Depending on the values they store, we have assigned the data types to the data members. For example, the 

The percentage of a student can be ‘94.0” or 94.5”, so we have assigned the “float64” data type to it. 

Accessing Structure Members

The data members of a structure are accessed using the dot “.” operator. For accessing structure members, we will create structure variables.

Example:

ar stud1 student

We have created a structure variable called “stud1”; through this, we will access the structure members.

stud1.id

stud1.name

stud1.percentage

Stud1.rank

5. Recover, Defer, and Panic

Recover is a built-in function in Go. It is used to regain control of a program from error conditions. It resumes the normal execution and stops the terminating sequence.

The defer keyword is used to postpone the execution of a function or statement until the calling function ends. They are generally used for executing closing statements.

Panic is a built-in function in Golang. It is similar to throwing an exception like in other languages. It is used when normal execution flow stops immediately, but the deferred functions are executed normally. 

Advanced concepts of Golang Programming Language

1. Error Handling

In every program, we will face some errors during the execution of the program or after the execution of the program. To handle those errors in Go programs, we have a simple inbuilt framework. To build an error message, we use “errors. New”.

Example:

package main
import "fmt"
import "os"

//function accepts a filename and tries to open it.
func fileopen(name string) {
    f, er := os.Open(name)

    //er will be nil if the file exists else it returns an error object  
    if er != nil {
        fmt.Println(er)
        return
    }else{
    	fmt.Println("file opened", f.Name())
    }
}

func main() {  
    fileopen("invalid.txt")
}

2. Interfaces

Go Programming language supports interfaces to include methods in the Go Program.  Structures use methods to access data members.

Example:

package main

import ("fmt" "math")

// Define Interfaces
type Shape interface {
   area() float64
}

type Circle struct {
   x,y,radius float64
}

type Rectangle struct {
   width, height float64
}

func(circle Circle) area() float64 {
   return math.Pi * circle.radius * circle.radius
}

func(rect Rectangle) area() float64 {
   return rect.width * rect.height
}

func getArea(shape Shape) float64 {
   return shape.area()
}

func main() {
   circle := Circle{a:0,b:0,radius:5}
   rectangle := Rectangle {width:20, height:10}
   
   fmt.Printf("Circle area: %fn",getArea(circle))
   fmt.Printf("Rectangle area: %fn",getArea(rectangle))
}

3. Type Casting

Typecasting is a mechanism to change the data type of a particular variable. For example, if we store decimal values into an integer variable, we have to change the data type of that variable to float32.

Example

package mind
 
import "go1"
  
func main()
 
var a int = 10
var b int = 3
var c float32
 
c = float32(a) / float32(b) // converting the datatype of variables a and b from int to float32
 
go1.println(" value of c is : %f " ,c)
 
The output of the above program is ;
 
Value of c is: 3.3333

The integer variables a and b are converted into float variables.

4. Go Concurrency

Go supports the concurrent execution of tasks. It means executing multiple tasks simultaneously. Programs that run their smaller components at the same time are known as concurrency.

In Golang, concurrency is achieved using Goroutines and Channels.

  • Goroutines

A function or method that runs concurrently with other functions or methods is called Goroutine. They are much lighter than threads. Goroutine is invoked using the keyword go followed by a function call.

Example: 

package main
import "fmt"
    
func display() {
	for x:=5; x<10; x++ {
		fmt.Println("In display")
	}
}

func main() {
	//invoking the goroutine display()
	go display()
	//The main() continues without waiting for display()
	for x:=0; x<5; x++ {
		fmt.Println("In main")
	}
}
  • Channels

Channels are a way of communication for functions to associate with each other. It acts as a medium where one routine places data and is accessed by another routine in the Golang server.

Syntax:

channel_variable := make(chan datatype)

5. Go Mutex

A mutex is a method used as a locking mechanism to ensure that one Goroutine can access the critical section of code at any point. Two methods defined on Mutex are Lock and Unlock. 

If one Goroutine already has the lock, then the new Goroutine will be stopped until the mutex is unlocked. 

Example:

package main  
import (  
   "sync"  
   "time"  
   "math/rand"  
   "fmt"  
)  
var wait sync.WaitGroup  
var count int  
var mutex sync.Mutex  
func  increment(z string)  {  
   for a :=0;a<5;a++ {  
      mutex.Lock()  
      c := count  
      x++;  
      time.Sleep(time.Duration(rand.Intn(5))*time.Millisecond)  
      count = c;  
      fmt.Println(z, a,"Count: ",count)  
      mutex.Unlock()  
        
   }  
   wait.Done()  
     
}  
func main(){  
   wait.Add(2)  
   go increment("left: ")  
   go increment("right: ")  
   wait.Wait()  
   fmt.Println("last count value " ,count)  
}  

 

Golang Future

Golang programming language has a very bright future. In the last few years, it has skyrocketed to the top 10 of all language ranking indices. Today’s renowned companies like Facebook, Netflix, Uber, etc., are also using Golang. 

A survey by HackerEarth also shows that out of 16,655 developers, over 32% of working professionals referred to Go as “the most sought-after programming language.” This clearly indicates that the future is filled with opportunities for Golang developers.

You can expect even more experts to develop and manage Go projects in the coming future. The exciting and advanced features of Go will surely make it a contender for the next-generation programming language.

Conclusion

This brings us to the end of this Golang Tutorial. We hope everything shared in this tutorial is useful for you. Do stay tuned for more Golang-related blogs. If you have any queries related to the tutorial or want a blog post on any new topic from us, let us know in the comment section below, and we would like to help up.

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
BitBucket TrainingDec 07 to Dec 22View Details
BitBucket TrainingDec 10 to Dec 25View Details
BitBucket TrainingDec 14 to Dec 29View Details
BitBucket TrainingDec 17 to Jan 01View Details
Last updated: 03 Apr 2023
About Author

Ravindra Savaram is a Technical Lead at Mindmajix.com. His passion lies in writing articles on the most popular IT platforms including Machine learning, DevOps, Data Science, Artificial Intelligence, RPA, Deep Learning, and so on. You can stay up to date on all these technologies by following him on LinkedIn and Twitter.

read less