The Wayback Machine - https://web.archive.org/web/20240824142502/https://www.geeksforgeeks.org/golang-tutorial-learn-go-programming-language/
Open In App

Golang Tutorial – Learn Go Programming Language | Beginner to Advanced

Last Updated : 17 Mar, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.



Similar Reads

10 Best Books to Learn Go Programming Language [2024]
Golang or Go programming language was introduced first by Google in late 2007 and was released in 2009 by Robert Griesemer, Rob Pike, and Ken Thompson. It’s a free-to-use, open-source language that helps in making more reliable and effective software. There are approximately 1.1 million developers who opt for Go as their primary language. The reaso
10 min read
Learn Programming Languages- List of 11 Popular Programming Languages
In this rapidly growing world, programming languages are also rapidly expanding, and it is very hard to determine the exact number of programming languages. It is an essential part of software development because it creates a communication bridge between humans and computers. Now, if you are a beginner who wants to learn, search the internet, you w
9 min read
Top 7 Reasons to Learn Golang
Golang is an open-source, light-weight procedural programming language, developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language. It is currently ranked at 13 according to the popularity index, as opposed to 65th rank 2 years ago. Golang is widely used in production at G
4 min read
Object-Oriented Programming in GoLang
Object-oriented programming is a programming paradigm which uses the idea of "objects" to represent data and methods. Go does not strictly support object orientation but is a lightweight object Oriented language. Object Oriented Programming in Golang is different from that in other languages like C++ or Java due to factors mentioned below: 1. Struc
3 min read
Difference Between Go and Python Programming Language
Golang is a procedural programming language. It was developed in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson at Google but launched in 2009 as an open-source programming language. Programs are assembled by using packages, for efficient management of dependencies. This language also supports environment adopting patterns alike to dynamic la
2 min read
Auto Format Go Programming Language Source Code with gofmt
Formatting of source code adds an important feature to the quality and readability of the code. In Golang, we have built-in packages and commands to auto-format code in the source file as per the standards and best practices. We can use the gofmt command in the CLI to autoformat a Golang source file. We can autoformat the go code with gofmt package
4 min read
How to convert a slice of bytes in uppercase in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the uppercase usin
2 min read
Golang program that uses fallthrough keyword
With the help of fallthrough statement, we can use to transfer the program control just after the statement is executed in the switch cases even if the expression does not match. Normally, control will come out of the statement of switch just after the execution of first line after match. Don't put the fallthrough in the last statement of switch ca
2 min read
math.Lgamma() Function in Golang with Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Lgamma() function which is used to find the natural logarithm and sign (either -1 or +1) of Gamma(a). So, you need to add a math package in your program with the help of th
2 min read
math.Float64bits() Function in Golang With Examples
Go language provides inbuilt support for basic constants and mathematical functions to perform operations on the numbers with the help of the math package. This package provides Float64bits() function which returns the IEEE 754 binary representation of a with the sign bit of a and the result in the same bit position. So, you need to add a math pack
2 min read
How to check equality of slices of bytes in Golang?
In Go language slice is more powerful, flexible, and convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence that stores elements of a similar type, you are not allowed to store different types of elements in the same slice. In the Go slice of byes, you are allowed to check the equality of the slices w
3 min read
atomic.AddInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The AddInt64() function in Go language is used to automatically add delta to the *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax
3 min read
atomic.StoreInt64() Function in Golang With Examples
In Go language, atomic packages supply lower-level atomic memory that is helpful is implementing synchronization algorithms. The StoreInt64() function in Go language is used to atomically store val into *addr. This function is defined under the atomic package. Here, you need to import "sync/atomic" package in order to use these functions. Syntax: f
2 min read
reflect.FieldByIndex() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.FieldByIndex() Function in Golang is used to get the nested field corresponding to index. To access this function, one needs to imports the reflect package in the
2 min read
strings.Contains Function in Golang with Examples
strings.Contains Function in Golang is used to check the given letters present in the given string or not. If the letter is present in the given string, then it will return true, otherwise, return false. Syntax: func Contains(str, substr string) bool Here, str is the original string and substr is the string that you want to check. Let us discuss th
2 min read
bits.Sub() Function in Golang with Examples
The bits.Sub() Function in Golang is used to find the difference of a, b and borrow, i.e. diff = a - b - borrow. Here the borrow must be 0 or 1; otherwise, the behavior is undefined. To access this function, one needs to imports the math/bits package in the program. The return value of the borrowOutput will be always 0 or 1 in any case. Syntax: fun
2 min read
How to convert a slice of bytes in lowercase in Golang?
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In the Go slice of bytes, you are allowed to convert a slice in the lowercase usin
2 min read
io.PipeWriter.CloseWithError() Function in Golang with Examples
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The PipeWriter.CloseWithError() function in Go language is used to close the writer. However, successive reads from the PipeReader i.e, read half of the pipe will not return any
3 min read
Import in GoLang
Pre-requisite learning: Installing Go on Windows / Installing Go on MacOS Technically defining, a package is essentially a container of source code for some specific purpose. This means that the package is a capsule that holds multiple elements of drug/medicine binding them all together and protecting them in one mini shell. This capsule is easy to
9 min read
time.Round() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Round() function in Go language is used to find the outcome of rounding the stated duration 'd' to the closest multiple of 'm' duration. Here, the rounding manner for middle values is to round far off from 0. Moreover, this function is defined under th
2 min read
How to add a method to struct type in Golang?
Structs consist of data, but apart from this, structs also tell about the behavior in the form of methods. Methods attached to structs is very much similar to the definition of normal functions, the only variation is that you need to additionally specify its type. A normal function returning an integer and taking no parameter would look like. func
3 min read
Converting a string variable into Boolean, Integer or Float type in Golang
Various types of string conversions are needed while performing tasks in Golang. Package strconv is imported to perform conversions to and from string. String to Boolean Conversion ParseBool is used to convert string to boolean value. It accepts 1, t, T, TRUE, true, True as true and 0, f, F, FALSE, false, False as false. Any other value returns an
3 min read
Check if the given slice is sorted in Golang
In Go language slice is more powerful, flexible, convenient than an array, and is a lightweight data structure. The slice is a variable-length sequence which stores elements of a similar type, you are not allowed to store different type of elements in the same slice. In Go language, you can check the given slice is sorted or not with the help of Sl
3 min read
How to compare times in Golang?
With the help of Before() and After() and Equal(), function we can compare the time as well as date but we are also going to use the time.Now() and time.Now().Add() function for comparison. Functions Used: These functions compares the times as seconds. Before(temp) - This function is used to check if the given time is before the temporary time vari
2 min read
reflect.AppendSlice() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.AppendSlice() Function in Golang is used to appends a slice t to a slice s. To access this function, one needs to imports the reflect package in the program. Synta
2 min read
How to Deploy a Golang WebApp to Heroku?
Go, also known as "Golang," is gaining popularity among DevOps professionals in recent years. There are many tools written in Go, including Docker and Kubernetes, but they can also be used for web applications and APIs. While Golang can perform as fast as a compiled language, coding in it feels more like interpreting with standard tools such as a c
5 min read
reflect.ChanOf() Function in Golang with Examples
Go language provides inbuilt support implementation of run-time reflection and allowing a program to manipulate objects with arbitrary types with the help of reflect package. The reflect.ChanOf() Function in Golang is used to get the channel type with the given direction and element type, i.e., t represents int, ChanOf(RecvDir, t) represents <-c
1 min read
flag.Bool() Function in Golang With Examples
Go language provides inbuilt support for command-line parsing and has functions that could be used to define flags to be used with a command-line program using the flag package. This package provides the flag.Bool() function which is used to define a boolean flag with the specified name, default value, and usage string. Syntax: func Bool(name strin
2 min read
time.Sleep() Function in Golang With Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Sleep() function in Go language is used to stop the latest go-routine for at least the stated duration d. And a negative or zero duration of sleep will cause this method to return instantly. Moreover, this function is defined under the time package. He
3 min read
time.Time.Year() Function in Golang with Examples
In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Year() function in Go language is used to find the year in which the specified "t" happens. Moreover, this function is defined under the time package. Here, you need to import the "time" package in order to use these functions. Syntax: func (t Tim
2 min read
Article Tags :