Open In App

Golang Tutorial – Learn Go Programming Language | Beginner to Advanced

Improve
Improve
Like Article
Like
Save
Share
Report

This Golang tutorial provides you with all the insights into Go Language programming, Here we provide the basics, from how to install Golang to advanced concepts of Go programming with stable examples. So, if you are a professional and a beginner, this free Golang tutorial is the best place for your learning.

Golang, or Go Programming Language, is a statically typed and procedural programming language having syntax similar to C language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google. But they launched it in 2009 as an open-source programming language.

Golang-Tutorial-Learn-Go-Programming-Language

It provides a rich standard library, garbage collection, and dynamic-typing capability, and it also provides support for the environment to adopt patterns like dynamic languages. The latest version of the Golang is 1.20.3 released on 4th April 2023.

Prerequisites

Basic Programming Experience: Although it is not mandatory, one can easily learn Golang with any programming experience. But it is always good to have experience because it will help to know about the function.

IDE or Code Editor: Any text or code editor to write and edit codes.

Command Terminal: Go works using the terminal so any terminal is good to go.

Why to Learn Golang?

The main purpose of designing Golang was to eliminate the problems of existing languages. So let us see the problems that we are facing with Python, Java, C/C++ programming languages:

  • Python: It is easy to use but slow in comparison to Golang.
  • Java: It has a very complex type system.
  • C/C++: It has slow compilation time as well as a complex type system.
  • Also, all these languages were designed when multi-threading applications were rare, so not very effective to highly scalable, concurrent and parallel applications.
  • Threading consumes 1MB whereas Goroutine consumes 2KB of memory, hence at the same time, we can have millions of goroutine triggered.

Go Programming Language Key Features 

Here in this section, we have mentioned the most important Go Programming features. So, find out what Golang is becoming popular.

  • Golang supports environment-adopting patterns which is very similar to dynamic languages.
  • The compilation time of Golang is fast access to others.
  • Support concurrency and lightweight processes.
  • Golang supports Interfaces.
  • Go language programming supports generic programming.
  • It supports assertions.

Features-of-Golang

How to Download and Install Golang

Before we begin with the installation of Go, it is good to check if it might already be installed on your System. To check if your device is preinstalled with Golang or not, just go to the Command line (For Windows, search for cmd in the Run dialog (Window + R). Now run the following command:

go version

If Golang is already installed, it will generate a message with all the details of the Golang’s version available, otherwise, if Golang is not installed then an error will arise stating a Bad command or file name Before starting with the installation process, you need to download it. For that, all versions of Go for Windows are available on golang.org. 

Golang Downloads

Download the Golang according to your system architecture and follow the further instructions for the installation of Golang. 

Step 1: After downloading, unzip the downloaded archive file. After unzipping you will get a folder named go in the current directory. 

Extract-Golang-Files 

Step 2: Now copy and paste the extracted folder wherever you want to install this. Here we are installing in C drive. 

Step 3: Now set the environment variables. Right click on My PC and select 

Properties. Choose the Advanced System Settings from the left side and click on Environment Variables as shown in the below screenshots. 

Advanced-System-Settings 

Environment-Variables 

Step 4: Click on Path from the system variables, and then click Edit. Then click New and then add the Path with bin directory where you have pasted the Go folder. Here we are editing the path C:\go\bin and clicking OK as shown in the below screenshots. 

Environment Variables 

Adding-Path-Variables 

Step 5: Now create a new user variable which tells Go command where Golang libraries are present. For that click on New on User Variables as shown in the below screenshots. 

Enviornment-User-Variables 

Now fill the Variable name as GOROOT and Variable value is the path of your Golang folder. So here Variable Value is C:\go\. After Filling click OK.

 User-Variables 

After that Click Ok on Environment Variables and your setup is completed. Now Let’s check the Golang version by using the command go version on the command prompt.

 golang-version 

After completing the installation process, any IDE or text editor can be used to write Golang Codes and Run them on the IDE or the Command prompt with the use of command:

go run filename.go

Hello World! Program in Golang

To run a Go program you need a Go compiler. In Go compiler, first you create a program and save your program with extension .go, for example, first.go. 

Go
// First Go program
package main

import "fmt"

// Main function
func main() {

    fmt.Println("!... Hello World ...!")
}

Output:

!... Hello World ...!

Now we run this first.go file in the go compiler using the following command, i.e:

$ go run first.go

Hello-World-Golang 

For more details about the different terms used in this program, you can visit Hello World! in Golang

Identifiers and Keywords

Identifiers are the user-defined name of the program components. In Go Programming language, an identifier can be a variable name, function name, constant, statement labels, package name, or types. 

Example:

// Valid identifiers:
_geeks23
geeks
gek23sd
Geeks
geeKs
geeks_geeks

// Invalid identifiers:
212geeks
if
default

Keywords or Reserved words are the words in a language that are used for some internal process or represent some predefined actions. These words are therefore not allowed to use as an identifier. Doing this will result in a compile-time error. There are total 25 keywords present in the Go language as follows: 

Golang-Keywords

Example: 

Go
// Go program to illustrate 
// the use of keywords

// Here package keyword is used to 
// include the main package
// in the program
package main

// import keyword is used to 
// import "fmt" in your package
import "fmt"

// func is used to
// create function
func main() {

    // Here, var keyword is used 
    // to create variables
    // Pname, Lname, and Cname 
    // are the valid identifiers
    var Pname = "GeeksforGeeks" 
    var Lname = "Go Language" 
    var Cname = "Keywords"
    
    fmt.Printf("Portal name: %s", Pname)
    fmt.Printf("\nLanguage name: %s", Lname)
    fmt.Printf("\nChapter name: %s", Cname)

}

Output:

Portal name: GeeksforGeeks
Language name: Go Language
Chapter name: Keywords

Data Types

Data types specify the type of data that a valid Go variable can hold. In Go language, the type is divided into four categories which are as follows:

  1. Basic type: Numbers, strings, and booleans come under this category.
  2. Aggregate type: Array and structs come under this category.
  3. Reference type: Pointers, slices, maps, functions, and channels come under this category.
  4. Interface type

Here, we will discuss Basic Data Types in the Go language. The Basic Data Types are further categorized into three subcategories which are:

  1. Numbers
  2. Booleans
  3. Strings

Numbers: In Go language, numbers are divided into three sub-categories that are:

  • Integers: In Go language, both signed and unsigned integers are available in four different sizes as shown in the below table. The signed int is represented by int and the unsigned integer is represented by uint. 
    Golang-Integers
  • Floating-Point Numbers: In Go language, floating-point numbers are divided into two categories as shown in the below table: 
    Golang-Floating-Point-Numbers
  • Complex Numbers: The complex numbers are divided into two parts are shown in the below table. float32 and float64 are also part of these complex numbers. The in-built function creates a complex number from its imaginary and real part and in-built imaginary and real function extract those parts. 
    Golang-Complex-Numbers
    • Variable names must begin with a letter or an underscore(_). And the names may contain the letters ‘a-z’ or ’A-Z’ or digits 0-9 as well as the character ‘_’.
Geeks, geeks, _geeks23  // valid variable
123Geeks, 23geeks      // invalid variable

  • A variable name should not start with a digit.
234geeks  // illegal variable 

  • The name of the variable is case sensitive.
geeks and Geeks are two different variables

  • Keywords is not allowed to use as a variable name.
  • There is no limit on the length of the name of the variable, but it is advisable to use an optimum length of 4 – 15 letters only.

if : It is used to decide whether a certain statement or block of statements will be executed or not i.e if a certain condition is true then a block of statement is executed otherwise not. 

Syntax:

if(condition) {

   // Statements to execute if
   // condition is true
}

Flow Chart:

 if-statement-in-golang

if-else : if we want to do something else if the condition is false. Here comes the else statement. We can use the else statement with if statement to execute a block of code when the condition is false. 

Syntax:

 
if (condition) {

    // Executes this block if
    // condition is true
} else {

    // Executes this block if
    // condition is false
}

Flow Chart:

if-else-statement-in-golang

Nested if : Nested if statements mean an if statement inside an if statement. Yes, Golang allows us to nest if statements within if statements. i.e, we can place an if statement inside another if statement. 

Syntax:

if (condition1) {

   // Executes when condition1 is true
   
   if (condition2) {

      // Executes when condition2 is true
   }
}

Flow Chart: 

Nested-If-Else-In-Golang

if-else-if Ladder : Here, a user can decide among multiple options. The if statements are executed from the top down. As soon as one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the final else statement will be executed. 

Important Points:

  • if statement can have zero or one else’s and it must come after any else if’s.
  • if statement can have zero to many else if’s and it must come before the else.
  • None of the remaining else if’s or else’s will be tested if an else if succeeds,
  • The initialization statement is optional and executes before for loop starts. The initialization statement is always in a simple statement like variable declarations, increment or assignment statements, or function calls.
  • The condition statement holds a boolean expression, which is evaluated at the starting of each iteration of the loop. If the value of the conditional statement is true, then the loop executes.
  • The post statement is executed after the body of the for-loop. After the post statement, the condition statement evaluates again if the value of the conditional statement is false, then the loop ends.
  1. break
  2. goto
  3. continue
  • First, we call mul function like the normal function, i.e, mul(23, 45) and executes when the function called(Output: Result : 1035 ).
  • Second, we call mul() function as a defer function using defer keyword, i.e, defer mul(23, 56) and it executes(Output: Result: 1288 ) when all the surrounding methods return.

Golang Frequently Asked Questions

1. What is Go Language is used for?

Golang is originally used to build a program for networking and infrastructure infrastructure.

2. Is Go language is beginner language?

Go programming language is simple to learn and easy to read by other developers; hence, many of the developers call Golang a simple language for beginners.

3. Is it difficult ti learn Golang?

No, Golang is relatively easy to learn; if you have prior experience with C or C++, then it is one of the easiest programming languages to learn.

4. What is the hardest part of Golang?

It is not the hardest language to learn, but some of the topics in Golang, like error handling, concurrency, and dependency management, take time to learn.

5. How long will it take to learn Golang?

If you have experience in programming, then it will take 6 to 9 months to become a good Golang developer.



Last Updated : 17 Mar, 2024
Like Article
Save Article
Share your thoughts in the comments
Similar Reads