Intro To Go

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 251

1

Getting Started with Go Programming

In this tutorial, you will learn how to get started with Go programming and write our first Go
program.

Go is an open-source programming language developed by Google. It was created with these


things in mind:

• efficient execution

• efficient compilation

• ease of programming

That's why Go is very fast, expressive (easy to read and write code) and lightweight.

Running Go

The simplest way of running Go code is by using an online Go compiler like The Go Playground.
You can also easily install and run Go programming locally on your computer. For that,
visit Install Go on Windows, Linux, and macOS.

Writing Our First Go Program

To get familiar with the basic syntax of Go programming, let's write our first program.

// Print "Hello World!" message

package main
import "fmt"

func main() {
2

fmt.Println("Hello World!")
}

Output

Hello World!

Here are the different parts of this program.

1. The main() function


All Go programs start with the main() function.

func main() {
// code goes here
}

To use this function, we must import the main package first using package main.

Note: The line that starts with // is a comment. Comments are used to help users understand
the code; they are completely ignored by the Go compiler.

2. Print a line of text


To print a line of text in Go, we use the fmt.Println() function. The function displays the content
from the parentheses ().
To use fmt.Println(), we must import the fmt package first using import "fmt".

Basic Structure of a Go Program

Here are the things to take away from this tutorial.

1. All Go programs start from the main() function.


2. The bare minimum code structure of a Go program is:

package main

fun main() {

}
3

Frequently Asked Questions

Is the language called Go or Golang?


The official name of the language is plain Go.

The confusion between Go and Golang arose for the following reasons:

• The official Go website is golang.org; not go.org as this domain was not available.

• People started using the word Golang for their ease; assuming that Go(lang) is the short
form of Go Language.
What are the applications of Go Programming?
Originally, Go was developed to program networking and infrastructure-related stuff.

Today, Go has a wide range of applications like

• Data science and artificial intelligence.

• Network Server programming, Web programming.

• Robotics, Internet of Things, games, and microcontroller programming.

• Cloud-based applications and server-side applications.

• Data Scraping.

• In the future, Golang applications can run in androids as well.

Why should I use Go programming?


Go programming is for you if you are looking for these features:

• built-in testing

• support concurrency (can run multiple tasks at a time)

• fast, simple and lightweight

• efficient execution

• efficient compilation

• ease of programming

• interfaces to write modular and testable code

• garbage collection

• Is Go an object-oriented language?
4

• Go has features of a structural and object-oriented language. So, the answer can be
both yes and no.
• Go allows an object-oriented style of programming but it has no type of hierarchy.

Go Variables and Constants

In this tutorial, you will learn about variables and constants in Go programming with the help of
example.

Go Variables

In programming, a variable is a container that is used to store data. Here's how we can declare
a variable in Go programming.

var number int

Here,

• number - name of the variable


• var - keyword used to declare variable
• int - data type associated with the variable
Note: In Go, every variable has a fixed data type associated with it. The data type determines
the type of data that the variable can store.
For example, the number variable can only store integer data. It's because its type is int.
We will learn about different types of data types in detail in the next tutorial.

Assign Values to Go Variables

There are 3 ways to assign values to a variable.

Method 1

var number int = 10

Here, we have assigned an integer value 10 to the number variable.


Method 2
5

var number = 10

Here, we are not explicitly specifying the data type of the variable. In this case, the compiler
automatically detects the type by looking at the value of the variable.

Since the value 10 is an integer, the data type of number is int.


Method 3

number := 10

Here, we are using the := operator to assign the value 10 to the variable number. This is the
shorthand notation to assign values to variables.

Important Notes on Go Variables

1. If a variable is not assigned any value, a default value is assigned to it. For example,

var count int


fmt.Println(count)

Here, the count variable prints 0 (default value for int) because we haven't assigned any value
to it.
2. In Go, every variable must have a data type associated with it. If not, the program throws an
error.

// Error: count variable doesn't have a data type


var count

// count1 is of the int type


var count1 int

// count2 is of the int type


var count2 = 10
6

Example: Go Variables

package main
import "fmt"

func main() {

// explicitly declare the data type


var number1 int = 10
fmt.Println(number1)

// assign a value without declaring the data type


var number2 = 20
fmt.Println(number2)

// shorthand notation to define variable


number3 := 30
fmt.Println(number3)
}

Output

10
20
30

Changing Value of a Variable

As suggested by the name variable, we can change the value stored in a variable. For example,

// initial value
number := 10
fmt.println("Initial number value", number) // prints 10

// change variable value


number = 100
fmt.Println("The changed value", number) // prints 100
7

Initially, 10 was stored in the variable. Then, its value is changed to 100.
Note: In Go, we cannot change the type of variables after it is declared.
In the above example, the number variable can only store integer values. It cannot be used to
store other types of data. For example,

number := 10

// Error code
// assign string data
number = "Hello"

Creating Multiple Variables at Once

In Go, it's also possible to declare multiple variables at once by separating them with commas.
For example,

var name, age = "Palistha", 22

Here, "Palistha" is assigned to the name variable. Similarly, 22 is assigned to the age variable.
The same code above can also be written as:

name, age := "Palistha", 22

Rules of naming Variables

• A variable name consists of alphabets, digits, and an underscore.

• Variables cannot have other symbols ( $, @, #, etc).

• Variable names cannot begin with a number.

• A variable name cannot be a reserved word as they are part of the Go syntax
like int, type, for, etc.
8

By the way, we should always try to give meaningful variable names. This makes your code
easier to read and understand.

Illegal Variable Bad Variable Good Variable

1a a age

s@lary sal salary

first name fn firstName

annual-income annInc annualIncome

Constant in Go

Constants are the fixed values that cannot be changed once declared. In Go, we use
the const keyword to create constant variables. For example,

const lightSpeed = 299792458 // initial value

// Error! Constants cannot be changed


lightSpeed = 299792460

By the way, we cannot use the shorthand notation := to create constants. For example,

// Error code
const lightSpeed := 299792458

Go Data Types

In this tutorial, you will learn about data types in Go programming with the help of examples.
9

We use data types in Golang to determine the type of data associated with variables. For
example,

var age int

Here, int is a data type that specifies that the age variable can store integer data.
The basic data types in Golang are

Data
Description Examples
Types

int Integer numbers. 7123, 0, -5, 7023

float Numbers with decimal points. 20.2, 500.123456, -34.23

complex Complex numbers. 2+4i, -9.5+18.3i

"Hello World!", "1 is less


string Sequence of characters.
than 2"

bool Either true or false. true, false

A byte (8 bits) of non-negative


byte 2, 115, 97
integers.

Used for characters. Internally used as


rune 'a', '7', '<'
32-bit integers.

Now, let's discuss the commonly used data types in detail.


10

1. Integer Data Type

Integers are whole numbers that can have both zero, positive and negative values but no
decimal values. For example, 0, 5, -1340.
We commonly use the int keyword to declare integer numbers.

var id int

Here, id is a variable of type integer.


You can declare multiple variables at once in the same line.

var id, age int

In Go programming, there are two types of integers:

• signed integer int - can hold both positive and negative integers
• unsigned integer uint - can only hold positive integers
There are different variations of integers in Go programming.

Data type Size

int/uint either 32 bits (4 bytes) or 64 bits (8 bytes)

int8/uint8 8 bits (1 byte)

int16/uint16 16 bits (2 bytes)

int32/uint32 32 bits (4 bytes)

int64/uint64 64 bits ( 8 bytes)

Note: Unless we have a specific requirement, we usually use the int keyword to create integers.
11

Example 1: Understanding Integer Type

package main
import "fmt"

func main() {
var integer1 int
var integer2 int

integer1 = 5
integer2 = 10

fmt.Println(integer1)
fmt.Print(integer1)
}

Output

5
10

If you want to learn more about creating variables, visit Go Variables.

2. Float Data Type

The float type is used to hold values with decimal points. For example, 6.7, -34.2

Keywords used: float32, float64


Here's an example,

var salary float64

There are two sizes of floating-point data in Go programming.

Data Type Size


12

float32 32 bits (4 bytes)

float64 64 bits (8 bytes)

Note: If we define float variables without specifying size explicitly, the size of the variable will
be 64 bits. For example,

// the size of the variable is 64


salary := 5676.3

Example 2: Understanding Float Type

// Program to illustrate float32 and float64 with example

package main
import "fmt"

func main() {
var salary1 float32
var salary2 float64

salary1 = 50000.503882901

// can store decimals with greater precision


salary2 = 50000.503882901

fmt.Println(salary1)
fmt.Println(salary2)

Output

50000.504
50000.503882901
13

3. String Data Type

A string is a sequence of characters. For example, "Hello", "Hey there"


Keyword: string
Here's an example,

var message string

In Go, we use either double quotes or backticks to create strings.

var message string = "Hello World "


var message string = `Hello World`

Example 3: Understanding String Type

// Program to create string variables

package main
import "fmt"

func main() {
var message string
message = "Welcome to Programiz"

fmt.Println(message)

Output

Welcome to Programiz

4. Boolean Data Type


14

The boolean data type has one of two possible values either true or false.
Keyword: bool

var isValid bool

Example 4: Understanding bool Type

// Program to create boolean variables

package main
import "fmt"

func main() {
var boolValue bool
boolValue = false

fmt.Println(boolValue)
}

Output

false

We will learn about booleans in detail in the Go Comparison and Logical Operators tutorial.




Previous Tutorial:

Go Print Statement
15

In this tutorial, you will learn to print output messages to the screen in Go programming with
the help of examples.

We use these three functions to print output messages in Go programming.

• fmt.Print()
• fmt.Println()
• fmt.Printf()

Note: All these functions are defined under the fmt package. So, we must import
the fmt package before we can use these functions.

Go fmt.Print()

Let's take an example.

// Program to illustrate fmt.Print()

package main

// import fmt package


import "fmt"

func main() {

fmt.Print("Hello, ")
fmt.Print("World!")

Output

Hello World!

Here, the fmt.Print() function prints the content inside parentheses ().
16

Print Variables

Here's how we print variables in Go programming.

// Program to illustrate fmt.Print()

package main

// import the fmt package


import "fmt"

func main() {

name := "John"
fmt.Print(name)

Output

John

Note: We must not wrap variables inside quotation marks while printing. Otherwise, it's
considered as a string.

Printing Multiple Values At Once

We can print multiple values and variables at once by separating them with commas. For
example,

// Program to illustrate fmt.Print()

package main
17

// import the fmt package


import "fmt"

func main() {

name := "John"
fmt.Print("Name: ", name)
}

Output

Name: John

Go fmt.Println()

The way fmt.Println() works is similar to how fmt.Print() works with a couple of differences.
1. fmt.Println() prints a new line at the end by default.
2. If we print multiple values and variables at once, a space is added between the values by
default.

// Program to illustrate the use of Println() function

package main
import "fmt"

// prints output in different lines


func main() {

currentSalary := 50000

fmt.Println("Hello")
fmt.Println("World!")
fmt.Println("Current Salary:", currentSalary)

Output:
18

Hello
World!
Current Salary: 50000

Things to notice:
• All the output messages are printed in separate lines

• A space is added after Current Salary: by default

Go fmt.Printf()

The fmt.Printf() function formats the strings and sends them to the screen. Let's see an
example.

currentAge := 21
fmt.Printf("Age = %d", currentAge)

Here, the fmt.Printf() function replaces the %d with the value of currentAge.
By the way, %d is a format specifier that replaces integer variables with their values.

Printf() function in Go Programming

In Go, every data type has a unique format specifier.


19

Data Type Format Specifier

integer %d

float %g

string %s

bool %t

Example: Using %g to print Float Values

// Program to print an integer using its format specifier %g

package main
import "fmt"

func main() {
var number annualSalary = 65000.5

fmt.Printf("Annual Salary: %g", annualSalary)


}

Output

Annual Salary: 65000.5

Here, fmt.Printf() converts the "Annual Salary: %g" string to "Annual Salary: 65000.5".
20

Example: Using format specifiers to hold value of a variable

A format string may also have multiple format specifiers.

package main
import "fmt"

func main() {
var name = "John"
age := 23

fmt.Printf("%s is %d years old.", name, age)


}

Output

John is 23 years old.

Here's how this code works:

Working of Format Specifier in Go

Printing Without Package


21

It's also possible to print output without using the fmt package. For that, we
use print() and println(). For example,

// Program to print output using print() function

package main

func main() {
println("Using println instead of fmt.Println")

print("Using print instead of fmt.Print")


}

Output

Using println instead of fmt.Println


Using print instead of fmt.Print

Here, we have used println() and print() instead of fmt.Println() and fmt.Print() respectively.

Note: It's recommended to use the fmt package for printing. We usually
use println(), print() only for debugging purposes. To learn more, visit fmt.Println() Vs println()
in Go programming.

Go Take Input

In this tutorial, you will learn to take input from the user in Go programming with the help of
examples.

In Go, we use the scan() function to take input from the user. For example,

package main
import "fmt"

func main() {
var name string

// takes input value for name


fmt.Print("Enter your name: ")
fmt.Scan(&name)
22

fmt.Printf("Name: %s", name)

Output

Enter your name: Rosie


Name: Rosie

In the above example, the line

fmt.Scan(&name)

takes input value from the user and assigns it to the name variable.
Go programming provides three different variations of the Scan() method:
• fmt.Scan()
• fmt.Scanln()
• fmt.Scanf()

Note: All these functions are defined under the fmt package. So, we must import
the fmt package before we can use these functions.

Go fmt.Scan()

As mentioned earlier, the Scan() function takes input from the user. However, it can only take
input values up to a space.
When it encounters a space, the value before space is assigned to the specified variable. For
example,

package main
import "fmt"

func main() {
var language string

// takes input value for name


23

fmt.Print("Enter your favorite language: ")


fmt.Scan(&language)

fmt.Printf("Favorite Language: %s", language)

Output

Enter your favorite language: Go Programming


Favorite Language: Go

In the above example, we have provided the input value Go Programming. However, we are
only getting Go as the output.
This is because the Scan() function only takes input value up to the space.

Take Multiple Inputs Using Scan()

In Go, we can use the Scan() function to take multiple inputs from the user. For example,

package main
import "fmt"

func main() {

// create variables
var name string
var age int

// take name and age input


fmt.Println("Enter your name and age:")
fmt.Scan(&name, &age)

// print input values


fmt.Printf("Name: %s\nAge: %d", name, age)

}
24

Output

Enter your name and age:


Maria
27
Name: Maria
Age: 27

In the above example, we have created two variables, name and age. Notice that we have used
a single Scan() function to take input values for both variables.

fmt.Scan(&name, &age)

Here, we have provided two input values, Maria and 27 in two different lines (input values are
separated by newline). In this case, the value in the first line is assigned to the name variable
and the value in the second line is assigned to age.
We can also provide two values in a single line by separating them with space.

Output

Enter your name and age:


Maria 27
Name: Maria
Age: 27

In this case, the value before space is assigned to the first variable, name, and the value after
space is assigned to the second variable, age.

Go fmt.Scanln()

We use the Scanln() function to get input values up to the new line. When it encounters a new
line, it stops taking input values. For example,

package main
import "fmt"

func main() {
var name string
var age int
25

// take name and age input


fmt.Println("Enter your name and age:")
fmt.Scanln(&name, &age)

fmt.Printf("Name: %s\nAge: %d", name, age)

Output

Enter your name and age:


Maria
Name: Maria
Age: 0

In the above example, we have used the Scanln() function to take two input values
for name and age.

fmt.Scanln(&name, &age)

However, when we press enter after providing the first value, Maria, the program exits. This is
because Scanln() only takes input value up to the new line, so when it encounters the enter
after Maria, it stops taking input.
If we want to take input values for age, we must provide values separated by space.
Output

Enter your name and age:


Maria 27
Name: Maria
Age: 27

Here, we have separated two inputs by space, so Scanln() can take both input values.

Go fmt.Scanf()

The fmt.Scanf() function is similar to Scanln() function. The only difference is that Scanf() takes
inputs using format specifiers. For example,
26

// Program to take input from user using Scanf()

package main
import "fmt"

func main() {
var name string
var age int

// take name and age input using format specifier


fmt.Println("Enter your name and age:")
fmt.Scanf("%s %d", &name, &age)

fmt.Printf("Name: %s\nAge: %d", name, age)


}

Output

Enter your name and age:


Maria 27
Name: Maria
Age: 27

In the above example, we have used the Scanln() function to take two input values
for name and age using their respective format specifiers.

fmt.Scanf("%s %d", &name, &age)

Here,

• %s - specifies the string input which is assigned to the name variable


• %d - specifies the integer input which is assigned to the age variable
Just like Scanln(), the Scanf() function takes values separated by space. When it encounters a
new line, the Scanf() stops taking input values. That's why we have given inputs in the same
line, separated by a space.
In Go, every data type has a unique format specifier and we can use them to take input values
of each type using Scanf().
Data Type Format Specifier
27

integer %d

float %g

string %s

bool %t

Take Input of Float and Boolean Type

package main
import "fmt"

func main() {
var temperature float32
var sunny bool

// take float input


fmt.Println("Enter the current temperature:")
fmt.Scanf("%g", &temperature)

// take boolean input


fmt.Println("Is the day sunny?")
fmt.Scanf("%t", &sunny)

fmt.Printf("Current temperature: %g\nIs the day Sunny? %t", temperature, sunny)

Output

Enter the current temperature:


31.2
28

Is the day sunny?


true
Current temperature: 31.2
Is the day Sunny? true

In the above example, we have used %g to take the input of float32 type and %t to take the
input of bool type.
The input value 31.2 is assigned to the variable temperature and true is assigned to sunny.

Go Comments

In this tutorial, we will learn about Go comments and understand why they are important with
the help of examples.

In computer programming, comments are hints that are used to describe a piece of code. For
example,

// declare a variable
age := 24

// print variable
fmt.Println(age)

Here, // declare a variable and // print variables are two comments used in the code.
Comments have nothing to do with code logic. They are meant for fellow programmers and are
completely ignored by the compiler.

Types of Go Comments

In Go, there are two types of comments:

• // - Single Line comments


• /*...*/ - Multiline Comments
29

1. Single Line Comment in Go

In Go, we use two forward slashes // to create a single-line comment. For example,

package main
import "fmt"

func main() {

// declare a variable

age := 25

// print the variable

fmt.Println("Age is", age)


}

Output

Age is 25

In the above example, we have created a variable named age and printed it. Here, // declare a
variable and // print the variable are two single-line comments.
We can also use the single-line comment in the same line as the code. For example,

age := 25 // declare a variable

In this case, the compiler

• executes the code statement before //


• ignores the text after //

2. Multiline Comments in Go

In Go, a multiline comment starts with /* and ends with */. For example,

package main
import "fmt"
30

func main() {

/* creates a variable
to store the salary of the employee
*/

salary := 30000
fmt.Println("Salary:", salary)
}

Output

Salary: 30000

Here,

/* create a variable
to store the salary of the employee
*/

is a multiline comment.

Multiline comments are also called block comments and they extend for multiple lines.

Note: Multiline comments are generally used for debugging and testing purposes. In regular
use, it is recommended to use multiple single-line comments instead of /*...*/ to comment
multiple lines. For example,

// create a variable
// to store salary of the employee

Go Comments for Testing Code

Comments are helpful while debugging our code. For example,


31

Suppose we get an error while running a program. Instead of removing the whole code, we can
comment on some parts of the code and test the program.

Let's understand it with the following examples.

package main
import "fmt"

func main() {
age := 25
height := 170

fmt.Println("Age is", age)


}

This code throws an error because we have declared the height but have not used it anywhere.
Instead of removing the code of height, we can comment that. For example,

package main
import "fmt"

func main() {
age := 25

// height := 170

fmt.Println("Age is", age)


}

Output

Age is 25

Now, the code runs without any error.

Here, we have resolved the error by commenting the code related to height. Now, if we need
the value of height in the near future, we can simply uncomment it.

What are the advantages of Comments in Go?


Here are some of the major benefits of using comments:

1. Make Code Easier to Understand - Writing comments make our code readable and easier for
future reference.
32

2. Using Comments for debugging - Comments can be used to ignore a block of code that
causes an error during debugging.
3. Using Comments for efficient collaboration - Comments can help peer developers to
understand each other's code better.`
How to create better comments?
As Golang developers, our task is not only to write effective code. At times, our code will be
used in multiple projects. In such a case, a well-written comment might be a lifesaver.

We should always keep in mind the following points while writing comments.

• Use comments only to describe what a particular block of code does, now how it does.

• Don't overuse comments. Try to make our code self-explanatory.

• Try to use short and precise comments.

• Don't use redundant comments.

Go Operators

In this tutorial, you will learn about different operators in Go programming with the help of
examples.

In Computer Programming, an operator is a symbol that performs operations on a value or a


variable.

For example, + is an operator that is used to add two numbers.


Go programming provides wide range of operators that are categorized into following major
categories:

• Arithmetic operators

• Assignment operator

• Relational operators

• Logical operators

Arithmetic Operator
33

We use arithmetic operators to perform arithmetic operations like addition, subtraction,


multiplication, and division.

Here's a list of various arithmetic operators available in Go.

Operators Example

+ (Addition) a+b

- (Subtraction) a-b

* (Multiplication) a*b

/ (Division) a/b

% (Modulo Division) a%b

Example 1: Addition, Subtraction and Multiplication Operators

package main
import "fmt"

func main() {

num1 := 6
num2 := 2

// + adds two variables


sum := num1 + num2

fmt.Printf("%d + %d = %d\n", num1, num2, sum)

// - subtract two variables


34

difference := num1 - num2

fmt.Printf("%d - %d = %d\n",num1, num2, difference)

// * multiply two variables


product := num1 * num2

fmt.Printf("%d * %d is %d\n",num1, num2, product)

Output

6+2=8
6-2=4
6 * 2 = 12

Example 2: Golang Division Operator

package main
import "fmt"

func main() {

num1 := 11
num2 := 4

// / divide two integer variables


quotient := num1 / num2

fmt.Printf(" %d / %d = %d\n", num1, num2, quotient)

Output

11 / 4 = 2
35

In the above example, we have used the / operator to divide two numbers: 11 and 4. Here, we
get the output 2.
However, in normal calculation, 11 / 4 gives 2.75. This is because when we use the / operator
with integer values, we get the quotients instead of the actual result.

Division with integer

If we want the actual result we should always use the / operator with floating point numbers.
For example,

package main
import "fmt"

func main() {

num1 := 11.0
num2 := 4.0

// / divide two floating point variables


result := num1 / num2

fmt.Printf(" %g / %g = %g\n", num1, num2, result)

Output

11 / 4 = 2.75
36

Here, we get the actual result after division.

Example 3: Modulus Operator in Go

package main
import "fmt"

func main() {

num1 := 11
num2 := 4

// % modulo-divides two variables


remainder := num1 % num2

fmt.Println(remainder )

In the above example, we have used the modulo operator with numbers: 11 and 4. Here, we
get the result 3.
This is because in programming, the modulo operator always returns the remainder after
division.
37

Modulo Division in Go

Note: The modulo operator is always used with integer values.

Increment and Decrement Operator in Go

In Golang, we use ++ (increment) and -- (decrement) operators to increase and decrease the
value of a variable by 1 respectively. For example,

package main
import "fmt"

func main() {

num := 5

// increment of num by 1
num++
fmt.Println(num) // 6

// decrement of num by 1
num--
fmt.Println(num) // 4
38

In the above example,

• num++ - increases the value of num by 1, from 5 to 6


• num-- - decreases the value of num by 1, from 5 to 4
Note: We have used ++ and -- as prefixes (before variable). However, we can also use them as
postfixes (num++ and num--).
There is a slight difference between using increment and decrement operators as prefixes and
postfixes. To learn the difference, visit Increment and Decrement Operator as Prefix and
Postfix.

Go Assignment Operators

We use the assignment operator to assign values to a variable. For example,

var number = 34

Here, the = operator assigns the value on right (34) to the variable on left (number).

Example: Assignment Operator in Go

package main
import "fmt"

func main() {

num := 6
var result int

// = operator to assign the value of num to result


result = num
39

fmt.Println(result) // 6
}

In the above example, we have used the assignment operator to assign the value of
the num variable to the result variable.

Compound Assignment Operators

In Go, we can also use an assignment operator together with an arithmetic operator. For
example,

number := 2
number += 6

Here, += is additional assignment operator. It first adds 6 to the value of number (2) and
assigns the final result (8) to number.
Here's a list of various compound assignment operators available in Golang.

Operator Example Same as

+= (addition assignment) a += b a=a+b

-= (subtraction assignment) a -= b a=a-b

*= (multiplication assignment) a *= b a=a*b

/= (division assignment) a /= b a=a/b

%= (modulo assignment) a %= b a=a%b


40

Relational Operators in Golang

We use the relational operators to compare two values or variables. For example,

5 == 6

Here, == is a relational operator that checks if 5 is equal to 6.


A relational operator returns

• true if the comparison between two values is correct


• false if the comparison is wrong
Here's a list of various relational operators available in Go:

Operator Example Descriptions

== (equal to) a == b returns true if a and b are equal

!= (not equal to) a != b returns true if a and b are not equal

> (greater than) a>b returns true if a is greater than b

< (less than) a<b returns true if a is less than b

>= (greater than or returns true if a is either greater than or


a >= b
equal to) equal to b

<= (less than or equal returns true is a is either less than or


a <= b
to) equal to b

To learn more, visit Go relational operators.


41

Logical Operators in Go

We use the logical operators to perform logical operations. A logical operator returns
either true or false depending upon the conditions.
Operator Description Example

&& (Logical exp1 && returns true if both expressions exp1 and
AND) exp2 exp2 are true

returns true if any one of the expressions is


|| (Logical OR) exp1 || exp2
true.

returns true if exp is false and returns false if


! (Logical NOT) !exp
exp is true.

To learn more, visit Go logical operators.

More on Go Operators

Go Binary Right Shift Operator >>

Go Binary Left Shift Operator <<

What is the use of the & operator in Go?

What is the use of the*operator in Go?

If we use multiple operators together in a single statement, which operator is executed first?

Go Binary Right Shift Operator >>


The right shift operator shifts all bits towards the right by a certain number of specified bits.

Suppose we want to right shift a number 212 by some bits then,

212 = 11010100 (In binary)


212 >> 3 = 00011010 = 26 (Right shift by 3 bits)
42

212 >> 7 = 00000001 = 1 (Right shift by 7 bits)


212 >> 0 = 11010100 = 212 (No Shift)

For example,

package main
import "fmt"

func main() {
num := 212
for i := 0; i <= 3; i++ {

// right shift 212 by bits from 0 to 3


fmt.Printf("Right Shift by %d: %d\n", i, num>>i)

}
}

Output

Right Shift by 0: 212


Right Shift by 1: 106
Right Shift by 2: 53
Right Shift by 3: 26

Go Binary Left Shift Operator <<


The left shift operator shifts all bits towards the left by a certain number of specified bits. The
bit positions that have been vacated by the left shift operator are filled with 0.
Suppose we want to left shift a number 212 by some bits then,

212 = 11010100 (In binary)


212 << 1 = 110101000 = 424 (Adds one 0 to the right)
212 << 3 = 11010100000 = 1696 (Adds three 0's to the right)
212 << 0 = 11010100 = 212 (No Shift)

For example,

package main
import "fmt"

func main() {
num := 212
for i := 0; i <= 3; i++ {
43

// left shift 212 by bits from 0 to 3


fmt.Printf("Left Shift by %d: %d\n", i, num<<i)

}
}

Output

Left Shift by 0: 212


Left Shift by 1: 424
Left Shift by 2: 848
Left Shift by 3: 1696

What is the use of the & operator in Go?


In Go, & is the address operator that is used for pointers. It holds the memory address of a
variable. For example,

package main

import "fmt"

func main() {

num := 20

// &num prints the


// memory address where 20 is stored
fmt.Println(&num)

// Output: 0xc0000b8000

Here, we have used the * operator to declare the pointer variable. To learn more, visit Go
Pointers.
What is the use of the*operator in Go?
In Go, * is the dereferencing operator used to declare a pointer variable. A pointer variable
stores the memory address. For example,

package main
import "fmt"

func main() {
44

b := 20

// pointer declaration
var num *int = &b

// gives the memory address


fmt.Println(num)
}

// Output: 0xc00010a000

Here, we have used the * operator to declare the pointer variable. To learn more, visit Go
Pointers.
If we use multiple operators together in a single statement, which operator is executed first?
In Go, we use the concept called operator precedence which determines which operator is
executed first if multiple operators are used together. For example,

result := 32 / 8 + 2 * 9 -4

Here, the / operator is executed first followed by the * operator. The + and - operators are
respectively executed at last.
This is because operators with the higher precedence are executed first and operators with
lower precedence are executed last.

Go Type Casting

In this tutorial, you'll learn about Go type casting with the help of examples.

Type casting is the process of converting the value of one data type (integer, float, string) to
another data type. For example,

// variable of float type


var floatValue float = 9.8

// convert float to int


var intValue int = int(floatValue)

Here, int(floatValue) specifies that we are converting the float value 9.8 to 9.
Since we are manually performing the type conversion, this is called explicit type casting in Go.
45

Go Explicit Type Casting

Golang provides various predefined functions like int(), float32(), string(), etc to perform
explicit type casting.
Let's see some of the examples of explicit type casting:

Example: Go float to int conversion

package main
import "fmt"

func main() {

var floatValue float32 = 5.45

// type conversion from float to int


var intValue int = int(floatValue)

fmt.Printf("Float Value is %g\n", floatValue)


fmt.Printf("Integer Value is %d", intValue)
}

Output

Float Value is 5.45


Integer Value is 5

Here, we have used the function int() to convert the value from 5.45 to 5.
In this case, we are manually converting the type of one type to another. Hence, it is called
explicit type casting.

Example: Go int to float conversion

package main
46

import "fmt"

func main() {

var intValue int = 2

// type conversion from int to float


var floatValue float32 = float32(intValue)

fmt.Printf("Integer Value is %d\n", intValue)


fmt.Printf("Float Value is %f", floatValue)

Output:

Integer Value is 2
Float Value is 2.000000

Here, we have used the function float32() to convert an integer value to float. The integer
value 2 changed to 2.000000 after the type casting.

Implicit Type Casting in Go

In implicit type casting, one data type is automatically converted to another data type.
However, Go doesn't support implicit type casting. For example,

package main
import "fmt"

func main() {

// initialize integer variable to a floating-point number


var number int = 4.34

fmt.Printf("Number is %g", number)


47

In the above example, we have created an int type variable named number. Here, we are trying
to assign a floating point value 4.34 to the int variable.
When we run this program, we will get an error:

./prog.go:8:7: constant 4.34 truncated to integer

This is because Golang doesn't support implicit type conversion.

Example: Add int and float number using Go type casting

package main
import "fmt"

func main() {

var number1 int = 20


var number2 float32 = 5.7
var sum float32

// addition of different data types


sum = float32(number1) + number2

fmt.Printf("Sum is %g",sum)
}

Output:

Sum is 25.7

In the above example, we have created an integer variable named number1 and a float variable
named number2. Notice the line,

sum = float32(number1) + number2


48

Here, we are adding values of two different types (float and int). Since Go doesn't support
implicit type casting, we need to change the value of one type to another.
This is why we have used float32(number1) to convert the int type variable number
to float type.

Go Booleans (Relational and Logical Operators)

In this tutorial, you'll learn about Go Boolean with the help of examples. You will also learn
about the relational and logical operators in Go.

Go Boolean Data Types

A boolean data type represents logical entities. It can have two possible values: true or false.
We use the bool keyword to create boolean-type variables. For example,

package main
import "fmt"

func main() {

var boolTrue bool = true


var boolFalse bool = false

fmt.Println("The boolean values are", boolTrue, "and", boolFalse)


}

Output:

The boolean values are true and false

Relational Operators in Golang

We use the relational operators to compare two values or variables. For example,

number1 := 9
number2 := 3
49

result := number1 > number2

Here, > is a relational (comparison) operator. It compares whether number1 is greater


than number2.
Relational Operators use boolean values (true and false) to return the validity of a relation. It
returns:
• true if the comparison between operators is correct.
• false if the comparison between operators is incorrect.

Different Types of Relational Operators in Golang

Here's a list of various relational operators available in Go:

Operator Example Descriptions

== (equal to) a == b returns true if a and b are equal

!= (not equal to) a != b returns true if a and b are not equal

> (greater than) a>b returns true if a is greater than b

< (less than) a<b returns true if a is less than b

>= (greater than or returns true if a is either greater than or


a >= b
equal to) equal to b

<= (less than or equal returns true is a is either less than or


a <= b
to) equal to b
50

Example: Relational Operator in Go

// Program to illustrate the working of Relational Operators

package main
import "fmt"

func main() {

number1 := 12
number2 := 20
var result bool

// equal to operator
result = (number1 == number2)

fmt.Printf("%d == %d returns %t \n", number1, number2, result)

// not equal to operator


result = (number1 != number2)

fmt.Printf("%d != %d returns %t \n", number1, number2, result)

// greater than operator


result = (number1 > number2)

fmt.Printf("%d > %d returns %t \n", number1, number2, result)

// less than operator


result = (number1 < number2)

fmt.Printf("%d < %d returns %t \n", number1, number2, result)

Output

12 == 20 returns false
12 != 20 returns true
12 > 20 returns false
12 < 20 returns true
51

Logical Operators in Go

Logical operators return either true or false depending upon the conditions.
Operator Description Example

&& (Logical exp1 && returns true if both expressions exp1 and
AND) exp2 exp2 are true

returns true if any one of the expressions is


|| (Logical OR) exp1 || exp2
true.

returns true if exp is false and returns false if


! (Logical NOT) !exp
exp is true.

Example: Logical Operator in Go

// Program to illustrate the working of Logical Operator

package main
import "fmt"

func main() {

number1 := 6
number2 := 12
number3 := 6
var result bool

// returns false because number1 > number2 is false


result = (number1 > number2) && (number1 == number3)
52

fmt.Printf("Result of AND operator is %t \n", result)

// returns true because number1 == number3 is true


result = (number1 > number2) || (number1 == number3)

fmt.Printf("Result of OR operator is %t \n", result)

// returns false because number1 == number3 is true


result = !(number1 == number3);

fmt.Printf("Result of NOT operator is %t \n", result)

Output

Result of AND operator is false


Result of OR operator is true
Result of NOT operator is false

Go Boolean Expression

In programming, expressions that return boolean values: true or false are known as boolean
expressions. For example,

number1 := 5
number2 := 8

result := number1 > number2

Here, number1 > number2 is a boolean expression that returns false.


Why boolean expression?
Boolean expressions are used to create decision-making programs. Suppose we want to create
a program that determines whether a person can vote or not.

We can use a boolean expression to check if the age of that person is greater than 18. If true,
the person can vote. If false, cannot vote.
We will learn more about these decision-making programs in Go if...else.
53

Go if else

In this tutorial, we will learn to create decision making programs using the Go if...else
statements with the help of examples.

In computer programming, we use the if statement to run a block code only when a certain
condition is met.

For example, assigning grades (A, B, C) based on marks obtained by a student.


• if the percentage is above 90, assign grade A
• if the percentage is above 75, assign grade B
• if the percentage is above 65, assign grade C

Go if statement

The syntax of the if statement in Go programming is:

if test_condition {
// code
}

If test_condition evaluates to
• true - statements inside the body of if are executed.
• false - statements inside the body of if are not executed.
54

Worki
ng of if statement in Go programming

Example: Simple if statement in Golang

// Program to display a number if it is positive

package main
import "fmt"

func main() {
number := 15

// true if number is less than 0


if number > 0 {
fmt.Printf("%d is a positive number\n", number)
}

fmt.Println("Out of the loop")


}

Output

The positive number is 15


55

Out of the loop

In the above example, we have created a variable named number. Notice the test_condition,

number > 0

Here, since the variable number is greater than 0, the test_condition evaluates true.
If we change the variable to a negative integer. Let's say -5.

number := -5

Now, when we run the program, the output will be:

Keep Learning

This is because the value of number is less than 0. Hence, the test_condition evaluates to false.
And, the body of the if block is skipped.

Go if...else statement

The if statement may have an optional else block. The syntax of the if..else statement is:

if test_condition {
// run code if test_condition is true
} else {
// run code if test_condition is false
}

If test_condition evaluates to true,


• the code inside if is executed
• the code inside else is skipped
If test_condition evaluates to false,
• the code inside else is executed
• the code inside if is skipped
56

Working of if...else in Go programming

Example: if...else statement in Golang

package main
import "fmt"

func main() {
number := 10

// checks if number is greater than 0


if number > 0 {
fmt.Printf("%d is a positive number\n", number)
} else {
fmt.Printf("%d is a negative number\n", number)
}
}

Output

10 is a positive number

The number is 10, so the test condition number > 0 is evaluated to be true. Hence, the
statement inside the body of if is executed.
57

If we change the variable to a negative integer. Let's say -5.

number := -5

Now if we run the program, the output will be:

-5 is a negative number

Here, the test condition evaluates to false. Hence code inside the body of else is executed.

Note: The else statement must start in the same line where the if statement ends.

Go if...else if ladder

The if...else statement is used to execute a block of code among two alternatives.
However, if you need to make a choice between more than two alternatives, then we use
the else if statement.

if test_condition1 {
// code block 1
} else if test_condition2 {
// code block 2
}.
.
.
} else {
// code block 3
}

Here,

if test_condition1 evaluates to true


• code block 1 is executed
• code block 2 and code block 3 are skipped
if test_condition2 evaluates to true
• code block 2 is executed
• code block 1 and code block 3 are skipped
58

if both test conditions evaluates to false


• code block 3 is executed
• code block 1 and code block 2 are skipped

Working of if.. else if..else in Go programming.

Example: if...if else ladder statement in Golang

// Program to relate two integers using =, > or < symbol

package main
import "fmt"

func main() {

number1 := 12
number2 := 20

if number1 == number2 {
59

fmt.Printf("Result: %d == %d", number1, number2)


} else if number1 > number2 {
fmt.Printf("Result: %d > %d", number1, number2)
} else {
fmt.Printf("Result: %d < %d", number1, number2)
}
}

Output

Result: 12 < 20

Here, both the test conditions number1 == number2 and number1 > number2 are false. Hence
the code inside the else block is executed.

Go nested if statement

You can also use an if statement inside of an if statement. This is known as a nested
if statement.

// outer if statement
if test_condition1 {
// statements

// inner if...else statement


if test_condition2 {
// statements
}else {
// statements
}
}

Example: Nested if statement in Golang

package main
60

import "fmt"

func main() {

number1 := 12
number2 := 20

// outer if statement
if number1 >= number2 {

// inner if statement
if number1 == number2 {
fmt.Printf("Result: %d == %d", number1, number2)
// inner else statement
} else {
fmt.Printf("Result: %d > %d", number1, number2)
}

// outer else statement


} else {
fmt.Printf("Result: %d < %d", number1, number2)
}
}

Output

Result: 12 < 20

If the outer condition number1 >= number2 is true


• inner if condition number1 == number2 is checked
• if condition is true, code inside the inner if is executed
• if condition is false, code inside the inner else is executed
If the outer condition is false, the outer else statement is executed.

Go switch

In this tutorial, you will learn to create the switch statement in Go programming with the help
of examples.

In Go, the switch statement allows us to execute one code block among many alternatives.

Syntax
61

switch expression {
case 1:
// code block 1

case 2:
// code block 2

case 3:
// code block 3
...
...

default:
// default code block
}

The expression after the switch keyword is evaluated. If the result of the expression is equal to
• case 1 - code block 1 is executed
• case 2 - code block 2 is executed
• case 3 - code block 3 is executed
In case there is no match, the default code block is executed.

Note: We can also use if...else statements in place of switch. However, the syntax of the switch
is much cleaner and easier to write.

Flowchart of Switch Statement


62

Flowchart of
Switch Statement in Go

Example: switch case in Golang

// Program to print the day of the week using switch case

package main
import "fmt"

func main() {
dayOfWeek := 3

switch dayOfWeek {

case 1:
fmt.Println("Sunday")

case 2:
fmt.Println("Monday")

case 3:
fmt.Println("Tuesday")
63

case 4:
fmt.Println("Wednesday")

case 5:
fmt.Println("Thursday")

case 6:
fmt.Println("Friday")

case 7:
fmt.Println("Saturday")

default:
fmt.Println("Invalid day")
}
}

Output

Tuesday

In the above example, we have assigned 3 to the dayOfWeek variable. Now, the variable is
compared with the value of each case statement.
Since the value matches with case 3, the statement fmt.Println("Tuesday") inside the case is
executed.

Note: Unlike other programming languages like C and Java, we don't need to use break after
every case. This is because in Go, the switch statement terminates after the first matching case.

Go switch case with fallthrough

If we need to execute other cases after the matching case, we can use fallthrough inside the
case statement. For example,

// Program to print the day of the week using fallthrough in switch

package main
64

import "fmt"

func main() {
dayOfWeek := 3

switch dayOfWeek {

case 1:
fmt.Println("Sunday")

case 2:
fmt.Println("Monday")

case 3:
fmt.Println("Tuesday")
fallthrough

case 4:
fmt.Println("Wednesday")

case 5:
fmt.Println("Thursday")

case 6:
fmt.Println("Friday")

case 7:
fmt.Println("Saturday")

default:
fmt.Println("Invalid day")
}
}

Output

Tuesday
Wednesday

In the above example, the expression in switch matches case 3 so, Tuesday is printed.
However, Wednesday is also printed even if the case doesn't match.
This is because we have used fallthrough inside case 3.
65

Go switch with multiple cases

We can also use multiple values inside a single case block. In such case, the case block is
executed if the expression matches with one of the case values.

Let's see an example,

// Program to check if the day is a weekend or a weekday

package main
import "fmt"

func main() {
dayOfWeek := "Sunday"

switch dayOfWeek {
case "Saturday", "Sunday":
fmt.Println("Weekend")

case "Monday","Tuesday","Wednesday","Thursday","Friday":
fmt.Println("Weekday")

default:
fmt.Println("Invalid day")
}
}

Output

Weekend

In the above example, we have used multiple values for each case:

• case "Saturday", "Sunday" - executes if dayOfWeek is either Saturday or Sunday


• case "Monday", "Tuesday", "Wednesday", "Thursday", "Friday" - executes
if dayOfWeek is either one of the value
66

Golang switch without expression

In Go, the expression in switch is optional. If we don't use the expression, the switch statement
is true by default. For example,

// Program to check if it's February or not using switch without expression

package main
import "fmt"

func main() {
numberOfDays := 28

// switch without any expression


switch {

case 28 == numberOfDays:
fmt.Println("It's February")

default:
fmt.Println("Not February")
}
}

Output

It's February

In the above example, switch doesn't have an expression. Hence, the statement is true.

Go switch optional statement

In Golang, we can also use an optional statement along with the expression. The statement and
expression are separated by semicolons. For example,

// Program to check the day of a week using optional statement

package main
67

import "fmt"

func main() {

// switch with statement


switch day := 4; day {

case 1:
fmt.Println("Sunday")

case 2:
fmt.Println("Monday")

case 3:
fmt.Println("Tuesday")

case 4:
fmt.Println("Wednesday")

case 5:
fmt.Println("Thursday")

case 6:
fmt.Println("Friday")

case 7:
fmt.Println("Saturday")

default:
fmt.Println("Invalid Day!")
}
}

Output

Wednesday

In the above example, we have used the optional statement day := 4 along with the
expression day. It matches case 4 and hence, Wednesday is printed.

Go for Loop
68

In this tutorial, you will learn about the Golang for loop with the help of examples.

In programming, a loop is used to repeat a block of code. For example,

If we want to print a statement 100 times, instead of writing the same print statement 100
times, we can use a loop to execute the same code 100 times.

This is just a simple example; we use for loops to clean and simplify complex programs.

Golang for loop

In Golang, we use the for loop to repeat a block of code until the specified condition is met.
Here's the syntax of the for loop in Golang.

for initialization; condition; update {


statement(s)
}

Here,

1. The initialization initializes and/or declares variables and is executed only once.
2. Then, the condition is evaluated. If the condition is true, the body of the for loop is
executed.
3. The update updates the value of initialization.
4. The condition is evaluated again. The process continues until the condition is false.
5. If the condition is false, the for loop ends.

Working of for loop


69

Flow Diagram of for loop in Go

Example 1: Golang for loop

// Program to print the first 5 natural numbers

package main
import "fmt"

func main() {

// for loop terminates when i becomes 6


for i := 1; i <= 5; i++ {
fmt.Println(i)
}

Output

1
2
3
70

4
5

Here is how this program works.

Iteration Variable Condition: i Action

1 is printed.
1st i=1 true
i is increased to 2.

2 is printed.
2nd i=2 true
i is increased to 3.

3 is printed.
3rd i=3 true
i is increased to 4.

4 is printed.
4th i=4 true
i is increased to 5.

5 is printed.
5th i=5 true
i is increased to 6.

6th i=6 false The loop is terminated.

Example 2: Golang for loop

// Program to print numbers for natural numbers 1 + 2 + 3 + ... +n

package main
import "fmt"

func main() {
var n, sum = 10, 0

for i := 1 ; i <= n; i++ {


sum += i // sum = sum + i
}
71

fmt.Println("sum =", sum)


}

Output

sum = 55

Here, we have used a for loop to iterate from i equal to 1 to 10.


In each iteration of the loop, we have added the value of i to the sum variable.

Related Golang for Loop Topics

Range form of the Golang for loop

Using Golang for loop as a while loop


What is an infinite loop?

Golang Blank Identifier in for loop.

Range form of the Golang for loop


In Go, we can use range with for loop to iterate over an array. For example,

package main
import "fmt"

func main() {

// create an array
numbers := [5] int {11, 22, 33, 44, 55}

// for loop with range


for item := range numbers {
fmt.Println(numbers[item])
}
72

Output

11
22
33
44
55

Here, we have used range to iterate 5 times (the size of the array).

The value of the item is 11 in the first iteration, 22 in the second iteration, and so on.

To learn more about arrays, visit Golang Arrays


Using Golang for loop as a while loop
In Golang, for loop can also be used as a while loop (like in other languages). For example,

for condition {
statement(s)
}

Here, the for loop only contains the test condition. And, the loop gets executed until the
condition is true. When the condition is false, the loop terminates.
What is an infinite loop?
A loop that never terminates is called an infinite loop.

If the test condition of a loop never evaluates to true, the loop continues forever. For example,

// Program to infinitely iterate through the loop

package main
import "fmt"

func main() {

for i := 0; i <= 10; i-- {


fmt.Println("Welcome to Programiz")
}

Here, the condition i <= 10 never evaluates to false resulting in an infinite loop.
Output
73

Welcome to Programiz
Welcome to Programiz
Welcome to Programiz

If we want to create an infinite loop intentionally, Golang has a relatively simpler syntax for it.
Let's take the same example above.

// Program to infinitely iterate through the loop

package main
import "fmt"

func main() {

// for loop without initialization/condition/update


// infinite loop
for {
fmt.Println("Welcome to Programiz")
}

Golang Blank Identifier in for loop.


In Golang, we have to use every variable that we declare inside the body of the for loop. If not
used, it throws an error. We use a blank identifier _ to avoid this error.
Let's understand it with the following scenario.

numbers := [5] int {11, 22, 33, 44, 55}

// index variable is declared but not used


for index, item := range numbers {
// throws an error
fmt.Println(item)
}

Here, we get an error message index declared but not used.


To avoid this, we put _ in the first place to indicate that we don't need the first component of
the array( index ). Let's correct the above example with a blank identifier.
74

// Program to print the elements of the array

package main
import "fmt"

func main() {

numbers := [5] int {11, 22, 33, 44, 55}

for _, item := range numbers {


fmt.Println(item)
}

Output

11
22
33
44
55

Here, the program knows that the item indicates the second part of the array.

Go while Loop

In this tutorial, we will learn to implement a while loop in Go using the for loop with the help of
examples.

In Go, we use the while loop to execute a block of code until a certain condition is met.
Unlike other programming languages, Go doesn't have a dedicated keyword for a while loop.
However, we can use the for loop to perform the functionality of a while loop.
Syntax of Go while loop

for condition {
// code block
}

Here, the loop evaluates the condition. If the condition is:


• true - statements inside the loop are executed and condition is evaluated again
75

• false - the loop terminates

Flowchart of while loop in Go

Working of Go while loop

Example: Go while loop

// Program to print numbers between 1 and 5

package main
import ("fmt")

func main() {
number := 1

for number <= 5 {


fmt.Println(number)
number++
}
76

Output

1
2
3
4
5

Here, we have initialized the number to 1.


1. During the first iteration, the condition number <= 5 is true. Hence, 1 is printed on the
screen. Now, the value of number is increased to 2.
2. Again the test condition, number <= 5 is true. Hence, 2 is also printed on the screen and
the value of number is increased to 3.
3. This process continues until number becomes 6. Then, the condition number <= 5 will
be false and the loop terminates.

Create multiplication table using while loop

// Program to create a multiplication table of 5 using while loop

package main
import ("fmt")

func main() {
multiplier := 1

// run while loop for 10 times


for multiplier <= 10 {

// find the product


product := 5 * multiplier

// print the multiplication table in format 5 * 1 = 5


fmt.Printf("5 * %d = %d\n", multiplier, product)
multiplier++
}
77

Output

5*1=5
5 * 2 = 10
5 * 3 = 15
5 * 4 = 20
5 * 5 = 25
5 * 6 = 30
5 * 7 = 35
5 * 8 = 40
5 * 9 = 45
5 * 10 = 50

Here, we have initialized the multiplier := 1. In each iteration, the value of the multiplier gets
incremented by 1 until multiplier <= 10.

Go do...while Loop

In Go, we can use the same for loop to provide the functionality of a do while loop. For
example,

// Program to print number from 1 to 5

package main
import "fmt"

func main(){
number := 1

// loop that runs infinitely


for {

// condition to terminate the loop


if number > 5 {
break;
}
78

fmt.Printf("%d\n", number);
number ++

}
}

Output

1
2
3
4
5

Notice the if statement inside the for loop.

if number > 5 {
break;
}

This statement acts as the while clause inside a do...while loop and is used to terminate the
loop.

Go range

In this tutorial, we will learn to use Go for range with the help of examples.

In Go, we use range with the for loop to iterate through the elements of array, string, or map.
Before you learn about range, make sure you know the working of Golang for loop.

Go for range with Array

We can use the for range loop to access the individual index and element of an array. For
example,

// Program using range with array

package main
79

import "fmt"

func main() {

// array of numbers
numbers := [5]int{21, 24, 27, 30, 33}

// use range to iterate over the elements of array


for index, item := range numbers {
fmt.Printf("numbers[%d] = %d \n", index, item)
}

Output

numbers[0] = 21
numbers[1] = 24
numbers[2] = 27
numbers[3] = 30
numbers[4] = 33

In the above example, we have used the for range

for index, item := range numbers {

Here, the range keyword returns two items:


• array index: 0, 1, 2, and so on.
• array element at corresponding index: 21, 24, 27, and so on.
To learn more about arrays, visit Golang arrays.

range with string in Golang

In Go, we can also use the for range keyword with string to access individual characters of a
string along with their respective index. For example,

// Program using range with string


80

package main
import "fmt"

func main() {
string := "Golang"
fmt.Println("Index: Character")

// i access index of each character


// item access each character
for i, item := range string {
fmt.Printf("%d= %c \n", i, item)
}

Output

Index: Character
0: G
1: o
2: l
3: a
4: n
5: g

In the above example, we have used the for range to access the individual characters of the
string Golang along with their respective index.
To learn more about strings, visit Golang string.

for range with Go map

In Go, we can also use the for range keyword with map to access key-value pairs. For example,

// Program using range with map

package main
import "fmt"
81

func main() {

// create a map
subjectMarks := map[string]float32{"Java": 80, "Python": 81, "Golang": 85}
fmt.Println("Marks obtained:")

// use for range to iterate through the key-value pair


for subject, marks := range subjectMarks {
fmt.Println(subject, ":", marks)
}

Output

Marks Obtained:
Java: 80
Python: 81
Golang: 85

In every iteration, the loop iterates through the key-value pair of a map.

Iteration Subject Marks

1 Java 80

2 Python 81

3 Golang 85

To learn more about map, visit Golang map.

Access keys of Map using Go range

We can also use the for range to only access the keys of a map. For example,
82

// Program to retrieve the keys of a map

package main
import "fmt"

func main() {

// create a map
subjectMarks := map[string]float32{"Java": 80, "Python": 81, "Golang": 85}

fmt.Println("Subjects:")
for subject := range subjectMarks {
fmt.Println( subject)
}

Output

Subjects:
Java
Python
Golang

Here, we have used range to retrieve just the keys "Java", "Python", "Golang" of a
map subjectMarks.

Go break and continue

In this tutorial, you will learn about the break and continue statements in Golang with the help
of examples.

Go break

The break statement terminates the loop when it is encountered. For example,

for initialization; condition; update {


break

Here, irrespective of the condition of the for loop, the break statement terminates the loop.
83

Working of Go break statement

Working of break
statement with for loop in Golang

Example: Go break statement

package main
import "fmt"

func main() {
for i := 1 ; i <= 5 ; i++ {

// terminates the loop when i is equal to 3


if i == 3 {
break
}

fmt.Println(i)
}
84

Output

1
2

In the above example, we have used the for loop to print the value of i. Notice the use of
the break statement,

if i == 3 {
break
}

Here, when i is equal to 3, the break statement terminates the loop. Hence, the output doesn't
include values after 2.

break-nested-loop Go break statement with nested loops

When we use the break statement with nested loops, it terminates the inner loop. For example,

package main
import "fmt"

func main() {

// outer for loop


for i := 1; i <= 3; i++ {

// inner for loop


for j := 1; j <= 3; j++ {

// terminates the inner for loop only


if i==2 {
break
}

fmt.Println("i=", i, "j=", j)
}
85

}
}

Output

i = 1, j = 1
i = 1, j = 2
i = 1, j = 3
i = 3, j = 1
i = 3, j = 2
i = 3, j = 3

In the above example, we have used the break statement inside the inner for loop.

if i == 2 {
break
}

Here, when the value of i is 2, the break statement terminates the inner for loop.
Hence, we didn't get any output for value i = 2.

Go continue

In Go, the continue statement skips the current iteration of the loop. It passes the control flow
of the program to the next iteration. For example,

for initialization; condition; update {

if condition {
continue
}

Here, irrespective of the condition of the for loop, the continue statement skips the current
iteration of the loop.
86

Working of Go continue statement

Working of continue
statement with for loop in Golang

Example: Go continue statement

package main
import "fmt"

func main() {
for i := 1 ; i <= 5 ; i++ {

// skips the iteration when i is equal to 3


if i == 3 {
continue
}

fmt.Println(i)
}
}

Output
87

1
2
4
5

In the above example, we have used the for loop to print the value of i. Notice the use of
the continue statement,

if i == 3 {
continue
}

Here, when i is equal to 3, the continue statement is executed. Hence, it skips the current
iteration and starts the next iteration. The value 3 is not printed to the output.

Go continue statement with nested loops

When we use the continue statement with nested loops, it skips the current iteration of the
inner loop. For example,

package main
import "fmt"

func main() {
for i := 1; i <= 3; i++ {
for j := 1; j <= 3; j++ {

// skips the inner for loop only


if j==2 {
continue
}

fmt.Println("i=", i, "j=",j )

}
}
}
88

Output

i= 1 j= 1
i= 1 j= 3
i= 2 j= 1
i= 2 j= 3
i= 3 j= 1
i= 3 j= 3

In the above example, we have used the continue statement inside the inner for loop.

if j == 2 {
continue
}

Here, when the value of j is 2, the continue statement is executed. Hence, the value of j = 2 is
never displayed in the output.

Note: The break and continue statement is almost always used with decision-making
statements. To learn about decision-making, visit Golang if else.

Go Array

In this tutorial, you will learn about array in Golang programming with the help of examples.

An array is a collection of similar types of data. For example,

Suppose we need to record the age of 5 students. Instead of creating 5 separate variables, we
can simply create an array.
89

Array of age

Creating an array in Go

Here is a syntax to declare an array in Golang.

var array_variable = [size]datatype{elements of array}

Here, the size represents the length of an array. The list of elements of the array goes inside {}.
For example,

// Program to create an array and prints its elements

package main
import "fmt"

func main() {

// declare array variable of type integer


// defined size [size=5]
var arrayOfInteger = [5]int{1, 5, 8, 0, 3}

fmt.Println(arrayOfInteger)
90

Output

[1 5 8 0 3]

In the above example, we have created an array named arrayOfInteger. The int specifies that
the array arrayOfIntegers can only store integers.
Other ways to declare a Go array

Declare an array of undefined size


Shorthand notation to declare an array

Accessing array elements in Golang

In Go, each element in an array is associated with a number. The number is known as an array
index.
We can access elements of an array using the index number (0, 1, 2 …). For example,

// Program to access the array elements

package main
import "fmt"

func main() {
languages := [3]string{"Go", "Java", "C++"}

// access element at index 0


fmt.Println(languages[0]) // Go

// access element at index 2


fmt.Println(languages[2]) // C++

In the above example, we have created an array named languages.


91

Go Array Index
Here, we can see each array element is associated with the index number. And, we have used
the index number to access the elements.

Note: The array index always starts with 0. Hence, the first element of an array is present at
index 0, not 1.

Initialize an Array in Golang

We can also use index numbers to initialize an array. For example,

package main
import "fmt"

func main() {

// declare an array
var arrayOfIntegers[3] int
92

// elements are assigned using index


arrayOfIntegers[0] = 5
arrayOfIntegers[1] = 10
arrayOfIntegers[2] = 15

fmt.Println(arrayOfIntegers)
}

Output

[5 10 15]

Here, we have initialized an array arrayOfIntegers using the index number.


The arrayOfIntegers[0] = 5 represents that index 0 of arrayOfIntegers holds the value 5,
index 1 holds value 10 and so on.
Initialize specific elements of an array
In Golang, we can also initialize the specific element of the array during the declaration. For
example,

package main
import "fmt"

func main() {

// initialize the elements of index 0 and 3 only


arrayOfIntegers := [5]int{0: 7, 3: 9}

fmt.Println(arrayOfIntegers)
}

Output

[7 0 0 9 0]

Here, we have initialized the element at index 0 and 3 with values 7 and 9 respectively.
In this case, all other indexes are automatically initialized with value 0 (default value of integer).
93

Changing the array element in Go

To change an array element, we can simply reassign a new value to the specific index. For
example,

// Program to change element by assigning the desired index with a new value

package main
import "fmt"

func main() {
weather := [3]string{"Rainy", "Sunny", "Cloudy"}

// change the element of index 2


weather[2] = "Stromy"

fmt.Println(weather)
}

Output

[Rainy Sunny Stromy]

Here, we have reassigned a new value to index 2 to change the array element
from "Cloudy" to "Stromy".

Find the length of an Array in Go

In Golang, we can use the len() function to find the number of elements present inside the
array. For example,

package main
import "fmt"

func main() {

// create an array
var arrayOfIntegers = [...]int{1, 5, 8, 0, 3, 10}
94

// find the length of array using len()


length := len(arrayOfIntegers)

fmt.Println("The length of array is", length)


}

Output

The length of array is 6

Here, we have used len() to find the length of an array arrayOfIntegers.

Looping through an array in Go

In Go, we can also loop through each element of the array. For example,

package main
import "fmt"

func main() {
age := [...]int{12, 4, 5}

// loop through the array


for i := 0; i < len(age); i++ {
fmt.Println(age[i])
}

Output

12
4
5

Here, len() function returns the size of an array. The size of an array age is 3 here, so
the for loop iterates 3 times; until all 3 elements are printed.
95

Multidimensional array in Golang

Arrays we have mentioned till now are called one-dimensional arrays. However, we can declare
multidimensional arrays in Golang.

A multidimensional array is an array of arrays. That is, each element of a multidimensional array
is an array itself. For example,

// Program to illustrate multidimensional array

package main
import "fmt"

func main() {

// create a 2 dimensional array


arrayInteger := [2][2]int{{1, 2}, {3, 4}}

// access the values of 2d array


for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
fmt.Println(arrayInteger[i][j])
}
}
}

Output

1
2
3
4

Here, we have created a multidimensional array arrayInteger with 2 rows and 2 columns.
A multidimensional array can be treated like a matrix like this
96

2-dimensional array in Golang

Go Slice

In this tutorial, you will learn about the Go slice and its various operations with the help of
examples.

Slice is a collection of similar types of data, just like arrays.

However, unlike arrays, slice doesn't have a fixed size. We can add or remove elements from
the array.

Create slice in Golang

Here's how we create a slice in Golang:

numbers := []int{1, 2, 3, 4, 5}

Here,

• numbers - the name of the slice


• int - represents that the slice only includes integer numbers
• {1, 2, 3, 4, 5} - elements of the slice
You might have noticed that we have left the [] notation empty. This is because we can add
elements to a slice that will change its size.
Note: If we provide size inside the [] notation, it becomes an array. For example,
97

// this is an array
numbers := [5]int{1, 2, 3, 4, 5}

// this is a slice
numbers := []int{1, 2, 3, 4, 5}

Example Golang Slice

// Program to create a slice and print its elements

package main
import "fmt"

func main() {

// declare slice variable of type integer


numbers := []int{1, 2, 3, 4, 5}

// print the slice


fmt.Println("Numbers: ", numbers)
}

Output

Numbers: [1 2 3 4 5]

In the above example, we have created a slice named numbers. Here, int specifies that the
slice numbers can only store integers.
Note: We can also create a slice using the var keyword. For example,

var numbers = []int{1, 2, 3, 4}

Create slice from an array in Golang


98

In Go programming, we can also create a slice from an existing array. For example,

Suppose we have an array of numbers

numbers := [8]int{10, 20, 30, 40, 50, 60, 70, 80}

Now, we can slice the specified elements from this array to create a new slice.

sliceNumbers = numbers[4, 7]

Here,

• 4 is the start index from where we are slicing the array element
• 7 is the end index up to which we want to get array elements
While creating a slice from an array, the start index is inclusive and the end index is exclusive.
Hence, our slice will include elements [50, 60, 70].

Example: Create Slice from Array in Go

// Program to create a slice from an array

package main
import "fmt"

func main() {

// an integer array
numbers := [8]int{10, 20, 30, 40, 50, 60, 70, 80}

// create slice from an array


sliceNumbers := numbers[4 : 7]

fmt.Println(sliceNumbers)

Output
99

[50, 60, 70]

Slice Functions

In Go, slice provides various built-in functions that allow us to perform different operations on a
slice.

Functions Descriptions

append() adds element to a slice

copy() copy elements of one slice to another

Equal() compares two slices

len() find the length of a slice

Adds Element to a Slice

We use the append() function to add elements to a slice. For example,

// Program to add elements to a slice

package main
import "fmt"

func main() {
primeNumbers := []int{2, 3}
100

// add elements 5, 7 to the slice


primeNumbers = append(primeNumbers, 5, 7)

fmt.Println("Prime Numbers:", primeNumbers)


}

Output

Prime Numbers: [2 3 5 7]

Here, the code

primeNumbers = append(primeNumbers, 5, 7)

adds elements 5 and 7 to the primeNumbers.


We can also add all elements of one slice to another slice using the append() function. For
example,

// Program to add elements of one slice to another

package main
import "fmt"

func main() {

// create two slices


evenNumbers := []int{2, 4}
oddNumbers := []int{1, 3}

// add elements of oddNumbers to evenNumbers


evenNumbers = append(evenNumbers, oddNumbers...)

fmt.Println("Numbers:", evenNumbers)
}

Output

Numbers: [2 4 1 3]

Here, we have used append() to add the elements of oddNumbers to the list
of evenNumbers elements.
101

Copy Golang Slice

We can use the copy() function to copy elements of one slice to another. For example,

// Program to copy one slice to another

package main
import "fmt"

func main() {

// create two slices


primeNumbers := []int{2, 3, 5, 7}
numbers := []int{1, 2, 3}

// copy elements of primeNumbers to numbers


copy(numbers, primeNumbers)

// print numbers
fmt.Println("Numbers:", numbers)
}

Output

Numbers: [2 3 5]

In the above example, we are copying elements of primeNumbers to numbers.

copy(numbers, primeNumbers)

Here, only the first 3 elements of primeNumbers are copied to numbers. This is because the
size of numbers is 3 and it can only hold 3 elements.
The copy() function replaces all the elements of the destination array with the elements.

Find the Length of a Slice


102

We use the len() function to find the number of elements present inside the slice. For example,

// Program to find the length of a slice

package main
import "fmt"

func main() {

// create a slice of numbers


numbers := []int{1, 5, 8, 0, 3}

// find the length of the slice


length := len(numbers)

fmt.Println("Length:", numbers)

Output

Length: 5

Looping through Go Slice

In Go, we can use a for loop to iterate through a slice. For example,

// Program that loops over a slice using for loop

package main
import "fmt"

func main() {
numbers := []int{2, 4, 6, 8, 10}

// for loop that iterates through the slice


for i := 0; i < len(numbers); i++ {
fmt.Println(numbers[i])
103

Output

2
4
6
8
10

Here, len() function returns the size of a slice. The size of a slice numbers is 5, so the for loop
iterates 5 times.
Access elements of a slice
In Go, each element in a slice is associated with a number. The number is known as a slice
index.

We can access elements of a slice using the index number (0, 1, 2 …). For example,

// Program to access the slice elements

package main
import "fmt"

func main() {

languages := []string{"Go", "Java", "C++"}

// access element at index 0


fmt.Println(languages[0])

// access element at index 2


fmt.Println(languages[2])

// access elements from index 0 to index 2


fmt.Println(languages[0:3])

Output

Go
104

C++
[Go Java C++]

In the above example, we have created a slice named languages.

Elements of slice with its respective index.


Here, we can see each slice element is associated with the index number. And, we have used
the index number to access the elements.

Note: The slice index always starts with 0. Hence, the first element of a slice is present at
index 0, not 1

Change elements of a slice


We can use the same index number to change the value of a slice element. For example,

package main
import "fmt"

func main() {
weather := []string{"Rainy", "Sunny", "Cloudy"}

//change the element of index 2


weather[2] = "Stromy"

fmt.Println(weather)
}

Output
105

[Rainy Sunny Stromy]

Here, the value of index 2 changed from "Cloudy" to "Stromy".


Create a slice using make() function
In Go, we can also create a slice using the make() function. For example,

numbers := make([]int, 5, 7)

Here, we have created a slice of integer type.

• 5 is the length of the slice (number of elements present in the slice)


• 7 is the capacity of the slice (maximum size up to which a slice can be extended)
Let's see an example,

package main
import "fmt"

func main() {

// create a slice using make()


numbers := make([]int, 5, 7)

// add elements to numbers


numbers[0] = 13
numbers[1] = 23
numbers[2] = 33

fmt.Println("Numbers:", numbers)
}

Output

Numbers: [13 23 33 0 0]

Here, we have created the slice with length 5. However, we have only initialized 3 values to the
slice.
In this case, the remaining value is initialized with the default value 0.
Looping through a slice using for range
Apart from using for loop, we can also use for range to loop through a slice in Golang. For
example,

// Program that loops over a slice using for range loop


106

package main
import "fmt"

func main() {
numbers := []int{2, 4, 6, 8, 10}

// for range loop that iterates through a slice


for _, value := range numbers {
fmt.Println(value)
}

Output

2
4
6
8
10

Here, the for range loop iterates through the first element of the slice (2) to the last
element(10). To learn about range, visit Go range.

Go map

In this tutorial, you'll learn about the working of maps in Go programming with the help of
examples.

In Go, the map data structure stores elements in key/value pairs. Here, keys are unique
identifiers that are associated with each value on a map.
Create a map in Golang
The syntax to create a Go map is:

subjectMarks := map[string]float32{"Golang": 85, "Java": 80, "Python": 81}

This code creates a map named subjectMarks. Here,

• [string] - indicates that keys of the map are of string type


• float32 - indicates that values of the map are of float type
• {Golang", "Java", "Python"} - keys of the map
107

• {85, 80, 81} - values of the map

Example: Map in Golang

// Program to create a map and print its keys and values

package main
import "fmt"

func main() {

// create a map
subjectMarks := map[string]float32{"Golang": 85, "Java": 80, "Python": 81}

fmt.Println(subjectMarks)
}

Output

map[Golang:85 Java:80 Python:81]

Here, we have created a map and printed the key-values of a map.

Note: We can also create a map using var keyword. For example,

var subjectMarks = map[string]float32{"Golang": 85, "Java": 80, "Python": 81}

Access Values of a Map in Golang

We can access the value of a map by using the corresponding key. For example,

package main
import "fmt"
108

func main() {

// create a map
flowerColor := map[string]string{"Sunflower": "Yellow", "Jasmine": "White", "Hibiscus": "Red"}

// access value for key Sunflower


fmt.Println(flowerColor["Sunflower"]) // Yellow

// access value for key Hibiscus


fmt.Println(flowerColor["Hibiscus"]) // Red

Here, we have used expressions

• flowerColor["Sunflower"] to access the value of the key Sunflower


• flowerColor["Hibiscus"] to access the value of the key Hibiscus

Change value of a map in Golang

To change the value of a map, we can directly assign a new value to the corresponding key. For
example,

package main
import "fmt"

func main() {

// create a map
capital := map[string]string{ "Nepal": "Kathmandu", "US": "New York"}
fmt.Println("Initial Map: ", capital)

// change value of US to Washington DC


capital["US"] = "Washington DC"

fmt.Println("Updated Map: ", capital)


}
109

Output

Initial Map: map[Nepal: Kathmandu US: New York]


Updated Map: map[Nepal: Kathmandu US: Washington DC]

In the above example, we have changed the value of a map by re-assigning the key "US" with a
new value "Washington DC"

Add Element of Go Map Element

So far, we have created a map with a predefined set of elements. However, we can also add
elements to a map.

To add an element, we can assign a new value along with a new key. For example,

package main
import "fmt"

func main() {

// create a map
students := map[int]string{1: "John", 2: "Lily"}
fmt.Println("Initial Map: ", students)

// add element with key 3


students[3] = "Robin"

// add element with key 5


students[5] = "Julie"

fmt.Println("Updated Map: ", students)


}

Output

Initial Map: map[1:John 2:Lily]


Updated Map: map[1:John 2:Lily 3:Robin 5:Julie]
110

Here, the code

• students[3] = "Robin" - adds a new element with key 3 and value Robin
• students[5] = "Julie" - adds a new element with key 5 and value Julie

Delete Element of Go Map Element

To delete an element of the map, we can use the delete() function. For example,

package main
import "fmt"

func main() {

// create a map
personAge := map[string]int{"Hermione": 21, "Harry": 20, "John": 25}
fmt.Println("Initial Map: ", personAge)

// remove element of map with key John


delete(personAge, "John")

fmt.Println("Updated Map: ", personAge)


}

Output

Initial Map: map[Harry:20 Hermione:21 John:25]


Updated Map: map[Harry:20 Hermione:21]

Here, we have used the delete() function to remove the element denoted by the key "John".

delete(personAge, "John")

The function takes two arguments:

• personAge - name of the map


• John - key of the element which is to be deleted
111

Note: If the key passed to the delete() function is not present inside the map, the function does
nothing.

Looping through the map in Golang

We can use a Go for range loop to iterate through each element of the map. For example,

package main
import "fmt"

func main() {

// create a map
squaredNumber := map[int]int{2: 4, 3: 9, 4: 16, 5: 25}

// for-range loop to iterate through each key-value of map


for number, squared := range squaredNumber {
fmt.Printf("Square of %d is %d\n", number, squared)
}

Output

Square of 2 is 4
Square of 3 is 9
Square of 4 is 16
Square of 5 is 25

In the above code, the for range loop accesses each key/value pair of the map.

Working of the for range loop


Iteration number squared

1 2 4
112

2 3 9

3 4 16

4 5 25

Note: We have used the Printf() function to make our output look much cleaner and
understandable.

Create Go Map using the make() function


Till now, we have provided the initial values while creating a map. However, if we need to
create a map without any initial value, we can use the make() function.

package main
import "fmt"

func main() {

// create a map using make()


student := make(map[int]string)

// add elements to the map


student[1] = "Harry"
student[2] = "Lilly"
student[5] = "Harmonie"

fmt.Println(student)
}

Output

map[1:Harry 2:Lilly 5:Harmonie]

Once we create a map with the make() function, we can now perform all other operations
(change, delete, access) to the map.

Access Keys of a Golang Map


We can also use the for range to only access the keys of a map. For example,

package main
import "fmt"

func main() {
113

// create a map
places := map[string]string{"Nepal": "Kathmandu", "US": "Washington DC", "Norway": "Oslo"}

// access only the keys of the map


for country := range places {
fmt.Println(country)
}

Output

Nepal
US
Norway

Notice the use of the for range loop,

for country := range places {

Here, the second entity (capital) is not used because we only want to retrieve the
keys "Nepal", "US", "Norway" of the map.
Access Values of a Go Map using blank identifier
We use the blank identifier _ with the for range loop to access the values of a map. For
example,

package main
import "fmt"

func main() {
places := map[string]string{"Nepal": "Kathmandu", "US": "Washington DC", "Norway": "Oslo"}

for _, capital := range places {


fmt.Println(capital)
}

Output

Kathmandu
114

Washington DC
Oslo

Notice that we have used _ in place of the country (for keys). This is because if we have to use
every variable that we declare inside the body of the for loop.
So, if we have used country (variable to denote keys), then we must use that inside the loop.
Otherwise, we will get an error.

places := map[string]string{"Nepal": "Kathmandu", "US": "Washington DC", "Norway": "Oslo"}

// country variable is declared but not used


for country, capital := range places {
// throws an error
fmt.Println(capital)
}

Go struct

In this tutorial, you will learn about the struct type in Go programming with the help of
examples.

A struct is used to store variables of different data types. For example,

Suppose we want to store the name and age of a person. We can create two variables: name
and age and store value.

However, suppose we want to store the same information of multiple people.

In this case, creating variables for a person might be a tedious task. We can create a struct that
stores the name and age to overcome this.

And, we can use this same struct for every person.

Declare Go Struct

The syntax to declare a struct in Go is:

type StructureName struct {


115

// structure definition
}

Here,

1. struct - keyword used to define a structure


2. StructName - the name of the structure
Let's see an example,

type Person struct {


name string
age int
}

Here, we have declared a struct named Person. Inside the curly braces {}, the struct contains
two variables name and age.

Struct instances

A struct definition is just a blueprint. To use a struct, we need to create an instance of it. For
example,

type Person struct {


name string
age int
}

// create an instance of struct


var person1 Person

Here, we have created an instance person1 followed by the name of the struct Person.
Now, we can use the person1 instance to access and define the struct properties.

// define the value of name and age


person1 = Person("John", 25)

We can also directly define a struct while creating an instance of the struct. For example,
116

person1 := Person("John", 25)

Here, John will be assigned to the name variable and 25 will be assigned to the age variable of
the Person struct.

Example: Golang struct

package main
import "fmt"

func main() {

// declare a struct
type Person struct {
name string
age int
}

// assign value to struct while creating an instance


person1 := Person{ "John", 25}

fmt.Println(person1)

// define an instance
var person2 Person

// assign value to struct variables


person2 = Person {
name: "Sara",
age: 29,
}

fmt.Println(person2)
}

Output
117

{John 25}
{Sara 29}

Access a struct in Golang

We can access individual elements of a struct using the struct instances. For example,

// Program to access the individual elements of struct

package main
import "fmt"

func main() {

// declare a struct
type Rectangle struct {
length int
breadth int
}

// declare instance rect1 and defining the struct


rect := Rectangle{22, 12}

// access the length of the struct


fmt.Println("Length:", rect.length)

// access the breadth of the struct


fmt.Println("Breadth:", rect.breadth)

area := rect.length * rect.breadth


fmt.Println("Area:", area)

Output

Length: 22
118

Breadth: 12
Area: 264

Here, we have used the . (dot) symbol to access the property of a struct.
• rect.length - access the value of the length variable from the struct
• rect.breadth - access the value of the breadth variable from the struct

Function inside a Struct in Go

Go also allows us to create a function inside a struct. It treats function as a field of struct. For
example,

// Program to use function as a field of struct

package main
import "fmt"

// initialize the function Rectangle


type Rectangle func(int, int) int

// create structure
type rectanglePara struct {
length int
breadth int
color string

// function as a field of struct


rect Rectangle

func main() {

// assign values to struct variables


result := rectanglePara{
length: 10,
breadth: 20,
119

color: "Red",
rect: func(length int, breadth int) int {
return length * breadth
},

fmt.Println("Color of Rectangle: ", result.color)


fmt.Println("Area of Rectangle: ", result.rect(result.length, result.breadth))

Output

Color of Rectangle: Red


Area of Rectangle: 200

In the above example, we have defined a function Rectangle as a field of


struct rectanglePara and used the function to find the area of a rectangle.

Go String

In this tutorial, you will learn about the Go String and its various operations with the help of
examples.

A string is a sequence of characters. For example, "Golang" is a string that includes


characters: G, o, l, a, n, g.
We use double quotes to represent strings in Go. For example,

// using var
var name1 = "Go Programming"

// using shorthand notation


name2 := "Go Programming"

Here, both name1 and name2 are strings with the value "Go Programming".

Example: Golang String


120

// Program to create a string in Golang

package main
import "fmt"

func main() {

// create string using var


var message1 = "Hello,"

// create string using shorthand notation


message2 := "Welcome to Programiz"

fmt.Println(message1)
fmt.Println(message2)
}

Output

Hello,
Welcome to Programiz

Golang String using backtick (` `)

In Go, we can also represent strings using the tick mark notation. For example,

Program to represent a string with a backtick

package main
import "fmt"

func main() {

// represent string with ` `


message := `I love Go Programming`
121

fmt.Println(message)
}

Output

I love Go Programming

Access Characters of String in Go

We know that a string is a sequence of characters. Hence, we can access individual characters
of a string.

Just like the Go array, we use index numbers to access string characters. For example,

// Program to access individual character of string

package main
import "fmt"

func main() {

// create and initialize a string


name := "Programiz"

// access first character


fmt.Printf("%c\n", name[0]) // P

// access fourth character


fmt.Printf("%c\n", name[3]) // g

// access last character


fmt.Printf("%c", name[8]) // z
}

Remember a string index starts from 0, not 1.


122

Accessing Individual Character of a String in


Golang

Hence,

• name[0] - returns the first character of the string


• name[3] - returns the fourth character
• name[8] - returns the ninth (last) character

Find the length of a string

In Go, we use the len() function to find the length of a string. For example,

// Program to count the length of a string

package main
import "fmt"

func main() {

// create string
message := "Welcome to Programiz"

// use len() function to count length


123

stringLength := len(message)

fmt.Println("Length of a string is:", len(stringLength))

Output

Length of a string is: 20

Here, len() returns the number of characters present inside the string.

Join Two Strings Together

In Go, we can use the + operator to join (concatenates) strings together. For example,

// Program to concatenate two strings

package main
import "fmt"

func main() {
message1 := "I love"
message2 := "Go programming"

// concatenation using + operator


result := message1 + " " + message2

fmt.Println(result)

Output

I love Go programming

Here, we have used the + operator to join three strings: message1, " ", and message2.
124

Golang String Methods

In Go, the strings package provides various methods that can be used to perform different
operations on strings.

Functions Descriptions

Compare() compares two strings

Contains() checks if a substring is present inside a string

Replaces() replaces a substring with another substring

ToLower() converts a string to lowercase

ToUpper() converts a string to uppercase

Split() splits a string into multiple substrings

To use these methods, we must first import the strings package in our code.

import (
"fmt"
"strings"
)

Compare Two Strings in Go

We use the Compare() of the strings package to compare two strings. For example,
125

// Program to compare string using Compare()

package main
import (
"fmt"
"strings"
)

func main() {

// create three strings


string1 := "Programiz"
string2 := "Programiz Pro"
string3 := "Programiz"

// compare strings
fmt.Println(strings.Compare(string1, string2)) // -1
fmt.Println(strings.Compare(string2, string3)) // 1
fmt.Println(strings.Compare(string1, string3)) // 0

Here, we have used

strings.Compare(string1, string2)

to compare two strings: string1 and string2. The function returns:


• -1 because string1 is smaller than string2
• 1 because string2 is greater than string3
• 0 because string1 and string3 are equal

Note: We have imported strings at the beginning of the program and


used strings.Compare() not Compare().

Check if String contains Substring


126

To check if a substring is present inside a string, we use the Contains() method of the
Go strings package.
Let's see an example,

// Program to illustrate the use of Contains()

package main
import (
"fmt"
"strings"
)

func main() {

text := "Go Programming"


substring1 := "Go"
substring2 := "Golang"

// check if Go is present in Go Programming


result := strings.Contains(text, substring1)

fmt.Println(result)

// check if Golang is present in Go Programming


result = strings.Contains(text, substring2)

fmt.Println(result)
}

Output

true
false

Here, we get the output

• true because the substring "Go" is present inside the string "Go Programming"
• false because the substring "Golang" is not present inside the string "Go Programming"
127

Replace a String in Go

To replace a string, we use the Replace() method present inside the strings package. For
example,

// Program using Replace() to replace strings

package main
import (
"fmt"
"strings"
)

func main() {

text := "car"
fmt.Println("Old String:", text)

// replace r with t
replacedText := strings.Replace(text, "r", "t", 1)

fmt.Println("New String:", replacedText)


}

Output

Old String: car


New String: cat

Notice the use of the Replace() method

strings.Replace(text, "r", "t", 1)

Here,

• text - string where we perform the replace operation


• "r" - old character that needs to be replaced
• "t" - new character that replaces the old character
• 1 - represents how many old characters to be replaced
Note: If we need to replace multiple characters, we can change the value of numbers from 1 to
any other. For example,
128

// replace 2 r with 2 a
strings.Replace("Programiz", "r", "R", 2)

// Output: PRogRamiz

Change Case of Go String

The strings package provides

• ToUpper() - to change string to uppercase


• ToLower() - to change string to lowercase
We use the ToUpper() function to change the given string to uppercase. The
function ToUpper() is provided by the package strings. For example,

// Program to convert a string to uppercaseand lowercase

package main
import (
"fmt"
"strings"
)

func main() {

text1 := "go is fun to learn"

// convert to uppercase
text1 = strings.ToUpper(text1)

fmt.Println(text1)

text2 := "I LOVE GOLANG"

// convert to lowercase
text2 = strings.ToLower(text2)
fmt.Println(text2)
129

Output

GO IS FUN TO LEARN
i love golang

Split Strings in Golang

In Go, we can split a string into multiple substrings using the Split() method. For example,

package main
import (
"fmt"
"strings"
)

func main() {
var message = "I Love Golang"

// split string from space " "


splittedString := strings.Split(message, " ")

fmt.Println(splittedString)
}

// Output: [I Love Golang]

Notice the code,

strings.Split(message, " ")

Here, we split the string at " ". Hence, we get individual words as output.
The Split() method returns a slice of all the substrings. In our example, [I Love Golang] is a slice.
130

Other String Operations

Compare Golang Strings using ==



Create Strings from a Slice

Loop Through Strings in Golang

Escape Sequence in Golang String

We use escape characters to escape some of the characters present inside a string. For
example,

Suppose we need to include double quotes inside a string.

// include double quote


message := "This article is about "String" in Go Programming."

Since strings are represented by double quotes, the compiler will treat "This article is about " as
the string. Hence, the above code will cause an error.
To solve this issue, we can use the escape character \ in Go. For example,

// use the escape character


message := "This article is about \"String\" in Go Programming."

Now, the escape characters tell the compiler to escape double quotes and read the whole text.

Example: Escape Sequence

package main
import "fmt"

func main() {

// use escape character in string


message := "This article is about \"String\" in Go Programming."
131

fmt.Println(message)
}

// Output: This article is about "String" in Go Programming.

Note: \n and \t are other popular escape sequences that add a new line and tab inside a string.

Go Strings are Immutable

In Go, strings are immutable. This means once we create a string, we cannot change it.

To understand it, consider an example,

// create a string
message := "Go"

Here, we have created a string variable named message with the value "Go".
Now, suppose we want to change the string.

// add another string "String" to the previous string


message = message + " " + "String"

Here, we are using the + operator to add another string "String" to the previous string.
It looks like we can change the value of the previous string. However, this is not true. Let's see
what has happened here,

1. go creates the first string "Go"


2. It then creates another string by joining the first string with "String"
3. assigns the new string to message
4. the first string "Go" remains unchanged.
Compare Golang Strings using ==
In Go, we can also use the == operator to compare two strings. For example,

// Program to compare two strings using == operator


132

package main
import "fmt"

func main() {

// create 2 strings
string1 := "Programiz"
string2 := "programiz"

// compare two strings


result := string1 == string2

fmt.Println(result)
}

// Output: false

The == operator returns


• true - if two strings are equal
• false - if two strings are not equal

Note: The == operator is case sensitive. Hence, Programiz and programiz are not equal.

Create Strings from a Slice


In Go, we can also create a string by joining all the elements of a string slice. For example,

// Program to create a single string from slices of strings using Join()

package main
import (
"fmt"
"strings"
)

func main() {

// create a string slice


words := []string{"I", "love", "Golang"}

// join each element of the slice


message := strings.Join(words, " ")
fmt.Println(message)
133

// Output: I love Golang

Here, we have used the Join() method of the strings package to join each element of the slice.
To learn more about slice, visit Golang Slice.
Loop Through Strings in Golang
We use for range loop to iterate through each character of a Golang string. For example,

// Program to iterate through a string

package main
import "fmt"

func main() {
text := "Golang"

// for range loop to iterate through a string


for _, character := range text {
fmt.Printf("%c\n", character)
}

Output

G
o
l
a
n
g

To learn about the for range loop, visit Go for range.

Go Functions

In this tutorial, you'll learn about the working of functions (parameters and return values) in Go
programming with the help of examples.

We use functions to divide our code into smaller chunks to make our code looks clean and
easier to understand.
134

Basically, a function is a block of code that performs a specific task. For example, suppose we
want to write code to create a circle and rectangle and color them.

In this case, we can organize our code by creating three different functions:

• function to create a circle

• function to create a rectangle

• function to color

This way, our code will look more organized. Also, we can reuse the same function to color the
circle and rectangle. Hence, providing the benefits of code reusability.

Create a Go Function

In Golang, we use the func keyword to create a function.

func greet(){
// code
}

Here, greet() is the name of the function (denoted by ()) and code inside {....} indicates the
function body.
Let's now create a function that prints Good Morning.

// Program to define a function

package main
import "fmt"

// define a function
func greet() {
fmt.Println("Good Morning")
}

func main() {
135

When we run this program, we will not get the output.

This is because we are just defining a function. To execute a function, we need to call it first.

Function Call
We use the function's name followed by parenthesis to call a function.

greet()

Now, let's add a function call inside main().

// Program to define a function

package main
import "fmt"

// define a function
func greet() {
fmt.Println("Good Morning")
}

func main() {

// function call
greet()

Output

Good Morning

This time the function runs, and we get Good Morning as output.
136

Example: Golang Function

package main
import "fmt"

// function to add two numbers


func addNumbers() {
n1 := 12
n2 := 8

sum := n1 + n2
fmt.Println("Sum:", sum)
}

func main() {
// function call
addNumbers()
}

Output

Sum: 20

In the above example, we have created a function named addNumbers(). The function adds
two numbers and prints the sum.
Here's how the program works:
137

Working of function in Go

Function Parameters in Golang

In our last example, we have created a function that does a single task, adds two
numbers, 12 and 8.

func addNumbers() {
n1 := 12
n2 := 8
sum := n1 + n2
fmt.Println("Sum:", sum)
}

However, in real projects, we want our functions to work dynamically. That is, instead of
adding 12 and 8, the addNumbers() function should be able to add any two numbers.
In this case, we can create functions that accept external values and perform operations on
them. These additional parameters are known as function parameters.

Define Function with Parameters


Here's how we can create a function with parameters:

func addNumbers(n1 int, n2 int) {


138

// code
}

Now, the addNumbers() function accepts two parameters: n1 and n2. Here, int denotes that
both parameters are of integer type.
To call this function, we need to pass some values (known as function arguments).

// function call
addNumbers(21, 13)

Here, 21 and 13 are the function arguments that are passed to the addNumbers() function.

Example: Function Parameters

// Program to illustrate function parameters

package main
import "fmt"

// define a function with 2 parameters


func addNumbers(n1 int, n2 int) {

sum := n1 + n2
fmt.Println("Sum:", sum)
}

func main() {

// pass parameters in function call


addNumbers(21, 13)

Output

Sum: 34

Here's how the program works:


139

Working of Function with Parameters

The arguments are assigned to the function parameters when we call the function. 21 is
assigned to n1 and 13 is assigned to n2.
That's why when we add n1 and n2 inside the function, we get 34 (21 + 13).

Note: The function parameter data type should always match the data passed during the
function call. Here, the data type of n1 and n2 is int, so we have passed integer
values 21 and 13 during a function call.

Return Value from Go Function

In our last example, we have printed the value of the sum inside the function itself. However,
we can also return value from a function and use it anywhere in our program.

Here's how we can create a Go function that returns a value:

func addNumbers(n1 int, n2 int) int {


// code
return sum
}
140

Here, int before the opening curly bracket { indicates the return type of the function. In this
case, int means the function will return an integer value.
And return sum is the return statement that returns the value of the sum variable.
The function returns value to the place from where it is called, so we need to store the returned
value to a variable.

// function call
result := addNumbers(21, 13)

Here, we are storing the returned value to the result variable.

Example: Function Return Value

package main
import "fmt"

// function definition
func addNumbers(n1 int, n2 int) int {
sum := n1 + n2
return sum

func main() {

// function call
result := addNumbers(21, 13)

fmt.Println("Sum:",result)
}

Output

Sum: 34

In the above example, when the return statement is encountered, it returns the value of sum.
The returned value is assigned to the result variable inside main().
141

Here's how the program works.

Working of Go function with return values

The return statement should be the last statement of the function. When a return statement is
encountered, the function terminates.
Let's see an example,

package main
import "fmt"

// function definition
func addNumbers(n1 int, n2 int) int {
sum := n1 + n2
return sum

// code after return statement


fmt.Println("After return statement")

func main() {

// function call
result := addNumbers(21, 13)
fmt.Println("Sum:",result)
142

We get a "missing return at the end of function" error as we have added a line after the return
statement.

Return Multiple Values from Go Function

In Go, we can also return multiple values from a function. For example,

// Program to return multiple values from function

package main
import "fmt"

// function definition
func calculate(n1 int, n2 int) (int, int) {
sum := n1 + n2
difference := n1 - n2

// return two values


return sum, difference

func main() {

// function call
sum, difference := calculate(21, 13)

fmt.Println("Sum:", sum, "Difference:", difference)


}

Output

Sum: 34 Difference: 8

In the above example, we have created a function named calculate().

func calculate(n1 int, n2 int) (int, int) {


143

...
}

Here, (int, int) indicates that we are returning two integer values: sum and difference from the
function.
Since the function returns two values, we have used two variables while calling the function.

sum, difference = calculate(21, 13);

Benefits of Using Functions

Here are the benefits of using a function in programming:

1. Code Reusability
We can reuse the same function multiple times in our program. For example,

// Program to illustrate code reusability in function

package main
import "fmt"

// function definition
func getSquare(num int) {
square := num * num
fmt.Printf("Square of %d is %d\n", num, square)
}

// main function
func main() {

// call function 3 times


getSquare(3)
getSquare(5)
getSquare(10)
144

Output

Square of 3 is 9
Square of 5 is 25
Square of 10 is 100

In the above program, we have created the function named getSquare() to calculate the square
of a number.
Here, we are reusing the same function multiple times to calculate the square of different
numbers.

2. Code Readability
Functions help us break our code into chunks to make our program readable and easy to
understand. It also makes the code easier to maintain and debug.

Go Variable Scope

In this tutorial, you'll learn about local and global variables in Golang with the help of examples.

In Go, we can declare variables in two different scopes: local scope and global scope.

A variable scope specifies the region where we can access a variable. For example,

func addNumbers() {
sum := 5 + 4
}

Here, the sum variable is created inside the function, so it can only be accessed within it (local
scope). This type of variable is called a local variable.
Based on the scope, we can classify Go variables into two types:

• Local Variables

• Global Variables
145

Go Local Variables

When we declare variables inside a function, these variables will have a local scope (within the
function). We cannot access them outside the function.

These types of variables are called local variables. For example,

// Program to illustrate local variables

package main
import "fmt"

func addNumbers() {

// local variables
var sum int

sum = 5 + 9

func main() {

addNumbers()

// cannot access sum out of its local scope


fmt.Println("Sum is", sum)

Output

undefined: sum

Here, the sum variable is local to the addNumbers() function, so it can only be accessed within
the function.
That's why we get an error when we try to access the function from main().
146

To fix this issue, we can either return the value of the local variable and assign it to another
variable inside the main function. Or we can make the variable sum global.

Global Variables in Golang

When we declare variables before the main() function, these variables will have global scope.
We can access them from any part of the program.
These types of variables are called global variables. For example,

// Program to illustrate global variable

package main
import "fmt"

// declare global variable before main function


var sum int

func addNumbers () {

// local variable
sum = 9 + 5
}

func main() {

addNumbers()

// can access sum


fmt.Println("Sum is", sum)

Output
147

Sum is 14

This time we can access the sum variable from inside the main() function. This is because we
have created the sum variable as the global variable.

// outside the function


var sum int

Now, the sum will be accessible from any scope (region) of the program.
What are the default values of local variables and global variables?
When we declare local and global variables without assigning any values to them, they are
assigned to their default values.

In Go, the default values of int and float32 types are 0.

// Program to illustrate the default values of global and local variables

package main
import "fmt"

// global variable
var variable1 int

func defaultValues() {

// local variable
var variable2 float32

fmt.Println(variable1) // 0
fmt.Println(variable2) // 0

func main() {
defaultValues()
}

In the above example, we have initialized local and global variables. Regardless of where it's
initialized, the default values of both int and float32 are 0.
What happens if both local and global variables have the same name?
If we have local and global variables with the same variable names, the compiler gives priority
to the local variable. For example,
148

// Program to illustrate the priorities of variables

package main
import "fmt"

// define global variable


var random = "Global"

func main() {

// define local variable with same name


var random = "Local"

fmt.Println(random)

Output

Local

Here, both the local and global variables have common name random. When we print random,
it prints "Local", not "Global". That means the compiler is giving priority to the local variable
over the global variable.
Why is local variables preferred over global variables?
In some scenarios, the use of global variables is considered bad practice. It is because a global
variable can be accessed from any part of the program.

So, when one function changes the value of a global variable, other functions of the same
program might not know about the changed value. This way it might create inconsistency in the
value of global variables.

Let's see an example.

// Program to find the temperature

package main
import "fmt"

// global variable
149

var temperature float32 = 35

func findTemp1() {
temperature = 43
}

func findTemp2() {
temperature = 29
}

func main() {
fmt.Println("Initial Value:", temperature)
findTemp1()
fmt.Println("Value after findTemp1():", temperature)
findTemp2()
fmt.Println("Value after findTemp2():", temperature)
}

Output

Initial Value: 35
Value after findTemp1(): 43
Value after findTemp2(): 29

Here, we have created 2 functions to find the temperature. When the findTemp2() function
changes the value of temperature, findTemp1 might not know about the change.
So, findTemp1() assumes the value is the same as it had defined and keeps functioning
according to that value.
This can result in unexpected output and creates high confusion in larger programs.

Go Recursion

In this tutorial, you'll learn about recursion in Go programming with the help of examples.

In computer programming, a recursive function calls itself. For example,

func recurse() {
……
……
recurse()
}
150

Here, the recurse() function includes the function call within its body. Hence, it is a Go recursive
function and this technique is called recursion.
Before you learn about recursion, make sure to know Go Functions.

Example: Recursion in Golang

package main
import "fmt"

func countDown(number int) {

// display the number


fmt.Println(number)

// recursive call by decreasing number


countDown(number - 1)

func main() {
countDown(3)
}

Output

Countdown Starts:
3
2
1
0
-1

In the above example, we have created a function named countDown(). Note that we have
added the function call inside the function.
151

countDown(number - 1)

Here, this is a recursive function call and we are decreasing the value of number in each call.
However, this function will be executed infinitely because we have added the function call
directly within the function

To avoid infinite recursion, we use conditional statements and only call the function if the
condition is met.

Recursive Function with conditional statement

In this example, we will use an if...else statement to prevent the infinite recursion.

// Program to end the recursive function using if…else

package main
import "fmt"

func countDown(number int) {

if number > 0 {
fmt.Println(number)

// recursive call
countDown(number - 1)

} else {
// ends the recursive function
fmt.Println("Countdown Stops")
}

func main() {
countDown(3)
}

Output
152

Countdown Starts
3
Countdown Starts
2
Countdown Starts
1
Countdown Starts
Countdown Stops

In the above example, we have added the recursive call inside the if statement.

if number > 0 {
fmt.Println(number)

// recursive call
countDown(number - 1)
}

Here, we are calling the function only if the number is greater than 0.
If the number is not greater than 0, the recursion ends. This is called the stopping condition.
Working of the program
number > 0 Print Recursive Call

true 3 countDown(2)

true 2 countDown(1)

true 1 countDown(0)

false Countdown stops function execution stops


153

Recursion in Golang

Example: Go program to calculate the sum of positive numbers

package main
import "fmt"

func sum(number int) int {

// condition to break recursion


if number == 0 {
return 0
} else {
return number + sum(number-1)
}
}

func main() {
var num = 50

// function call
var result = sum(num)

fmt.Println("Sum:", result)
154

Output

Sum: 1275

In the above example, we have created a recursive function named sum() that calls itself if the
value of number is not equal to 0.

return number + sum(number - 1)

In each iteration, we are calling the function by decreasing the value of number by 1.
Here's how the program works:

• In first call, the value of number is 50 which is not equal to 0. So, the else block is
executed which returns 50 + sum(49).
• Again, 49 is not equal to 0, so return 49 + sum(48) is executed.
• This process continues until number becomes 0. When number is 0, return 0 is
executed and it is added to the other values.
• Hence, finally, 50 + 49 + 48 + ...... + 0 is computed and returned to the main() function.

Factorial of a number using Go Recursion

package main
import "fmt"

func factorial (num int) int {

// condition to break recursion


if num == 0 {
return 1
} else {
// condition for recursion call
return num * factorial (num-1)
}
}

func main() {
155

var number = 3

// function call
var result = factorial (number)

fmt.Println("The factorial of 3 is", result)


}

Output

The factorial of 3 is 6

In the above example, we have created a recursive function named factorial() that calls itself if
the value of num is not equal to 0.

return num * factorial(num - 1)

In each call, we are decreasing the value of num by 1.


Here's how the program works:

Computing
Factorial Using Recursion

Go Anonymous Function

In this tutorial, you'll learn about the working of anonymous function in Go with the help of
examples.
156

In Go, we can create a function without the function name, known as an anonymous function.
For example,

func () {
fmt.Println("Function without name")
}

The above function is a valid function that prints "Function without name". It works just like a
regular function in Go.

Working of Go Anonymous Function

Since an anonymous function doesn't have any name, you might be wondering how we can call
the function.

Usually, what we do is assign the anonymous function to a variable and then use the variable
name to call the function. For example,

//anonymous function
var greet = func (){
// code
}

// function call
greet()

Here, you can see that we have used the variable name greet to call the function.
Example: Go Anonymous Function

package main
import "fmt"

func main() {

// anonymous function
var greet = func() {
fmt.Println("Hello, how are you")
157

// function call
greet()

Output

Hello, how are you

Here, we have assigned the anonymous function to the variable greet and used greet() to call
the function.

Anonymous Function with Parameters

Like a regular function, an anonymous function can also accept function parameters. For
example,

// Program to pass arguments in an anonymous function

package main
import "fmt"

func main() {

// anonymous function with arguments


var sum = func(n1, n2 int) {
sum := n1 + n2
fmt.Println("Sum is:", sum)
}

// function call
sum(5, 3)

Output
158

Sum is: 8

Here, the anonymous function takes two integer arguments n1 and n2.

func(n1, n2 int) {
...
}

Since we have assigned the anonymous function to the sum variable, we are calling the
function using the variable name.

sum(5, 3)

Here, 5 and 3 are values passed to the function.

Return Value From Anonymous Function

Like in regular functions, we can also return a value from an anonymous function. For example,

// Program to return value from an anonymous function

package main
import "fmt"

func main() {

// anonymous function
var sum = func(n1, n2 int) int {
sum := n1 + n2

return sum
}

// function call
result := sum(5, 3)

fmt.Println("Sum is:", result)


159

Output

Sum is: 8

Here, we have assigned the anonymous function func(n1,n2 int) int to the sum variable. The
function calculates the sum of n1 and n2 and returns it.

Example: Return Value From Anonymous Function

// Program to return the area of a rectangle

package main
import "fmt"

func main() {

// anonymous function
area := func(length, breadth int) int {
return length * breadth
}

// function call using variable name


fmt.Println("The area of rectangle is", area(3,4))

Output

The area of rectangle is 12

In the above program, we have defined an anonymous function and assigned it to the
variable area. The area of the rectangle, length * breadth (3 * 4), is returned to the area.
160

Anonymous Function as Arguments to Other Functions

In Go, we can also pass anonymous functions as arguments to other functions. In that case, we
pass the variable that contains the anonymous function. For example,

package main
import "fmt"

var sum = 0

// regular function to calculate square of numbers


func findSquare(num int) int {
square := num * num
return square
}

func main() {

// anonymous function that returns sum of numbers


sum := func(number1 int, number2 int) int {
return number1 + number2
}

// function call
result := findSquare(sum(6, 9))

fmt.Println("Result is:", result)

Output

Result is: 225

In the above example, we have created two functions:

• an anonymous function to find the sum of two numbers

• a regular function, findSquare(), to find the square of a number.


Notice the function call inside main()

result := findSquare(sum(6, 9))


161

Here, we have passed the anonymous function as the function parameter to


the findSquare() function.
The anonymous function returns the sum of two parameters. This sum is then passed to
the findSquare() function, which returns the square of the sum.
So, in our program, the anonymous function first returns the sum of 6 and 9, which is 15.
This value is then passed to the findSquare() function, which returns the square of 15, which
is 225.

Return an Anonymous Function in Go

We can also return an anonymous function in Go. For that, we need to create an anonymous
function inside a regular function and return it. For example,

// Program to return an anonymous function

package main
import "fmt"

// function that returns an anonymous function


func displayNumber() func() int {

number := 10
return func() int {
number++
return number
}
}

func main() {

a := displayNumber()

fmt.Println(a())

}
162

Output

11

In the above program, notice this line in the displayNumber() function,

func displayNumber() func() int {

Here, the func() denotes that displayNumber() returns a function, whereas the int denotes that
the anonymous function returns an integer. Notice that displayNumber() is a regular function.
Inside the displayNumber() function, we have created an anonymous function.

return func() int {



}

Here, we are returning the anonymous function. So, when the displayNumber() function is
called, the anonymous function is also called and the incremented number is returned.

Go Closure

In this tutorial, you will learn about closures in Go programming with the help of examples.

Go closure is a nested function that allows us to access variables of the outer function even
after the outer function is closed.

Before we learn about closure, let's first revise the following concepts:

• Nested Functions

• Returning a function

Nested function in Golang

In Go, we can create a function inside another function. This is known as a nested function. For
example,

package main
import "fmt"
163

// outer function
func greet(name string) {

// inner function
var displayName = func() {
fmt.Println("Hi", name)
}

// call inner function


displayName()

func main() {

// call outer function


greet("John") // Hi John

In the above example, we have created an anonymous function inside the greet() function.
Here, var displayName = func() {...} is a nested function. The nested function works similar to
the normal function. It executes when displayName() is called inside the function greet().

Returning a function in Go

We can create a function that returns an anonymous function. For example,

package main
import "fmt"

func greet() func() {

return func() {
fmt.Println("Hi John")
}
164

func main() {

g1 := greet()
g1()
}

Output

Hi John

In the above example, we have created the greet() function.

func greet() func() {...}

Here, func() before the curly braces indicates that the function returns another function.
Also, if you look into the return statement of this function, we can see the function is returning
a function.

From main(), we call the greet() function.

g1 := greet()

Here, the returned function is now assigned to the g1 variable. Hence, g1() executes the nested
anonymous function.

Go Closures

As we have already discussed, closure is a nested function that helps us access the outer
function's variables even after the outer function is closed. Let's see an example.

package main
import "fmt"

// outer function
func greet() func() string {
165

// variable defined outside the inner function


name := "John"

// return a nested anonymous function


return func() string {
name = "Hi " + name
return name
}

func main() {

// call the outer function


message := greet()

// call the inner function


fmt.Println(message())

Output

Hi John

In the above example, we have created a function named greet() that returns a nested
anonymous function.
Here, when we call the function from main().

message := greet()

The returned function is now assigned to the message variable.


At this point, the execution of the outer function is completed, so the name variable should be
destroyed. However, when we call the anonymous function using

fmt.Println(message())

we are able to access the name variable of the outer function.


It's possible because the nested function now acts as a closure that closes the outer scope
variable within its scope even after the outer function is executed.
166

Let's see one more example to make this concept clear for you.

Example: Print Odd Numbers using Golang Closure

package main
import "fmt"

func calculate() func() int {


num := 1

// returns inner function


return func() int {
num = num + 2
return num
}

func main() {

// call the outer function


odd := calculate()

// call the inner function


fmt.Println(odd())
fmt.Println(odd())
fmt.Println(odd())

// call the outer function again


odd2 := calculate()
fmt.Println(odd2())

Output
167

3
5
7
3

In the above example,

odd := calculate()

This code executes the outer function calculate() and returns a closure to the odd number.
That's why we can access the num variable of calculate() even after completing the outer
function.
Again, when we call the outer function using

odd2 := calculate()

a new closure is returned. Hence, we get 3 again when we call odd2().

Closure helps in Data Isolation

As we see in the previous example, a new closure is returned every time we call the outer
function. Here, each returned closure is independent of one another, and the change in one
won't affect the other.

This helps us to work with multiple data in isolation from one another. Let's see an example.

package main
import "fmt"

func displayNumbers() func() int {


number := 0

// inner function
return func() int {
number++
return number
}
168

func main() {

// returns a closure
num1 := displayNumbers()

fmt.Println(num1())
fmt.Println(num1())
fmt.Println(num1())

// returns a new closure


num2 := displayNumbers()
fmt.Println(num2())
fmt.Println(num2())

Output

1
2
3
1
2

In the above example, the displayNumbers() function returns an anonymous function that
increases the number by 1.

return func() int {


number++
return number
}

Inside the main() function, we assign the function call to num1 and num2 variables.
Here, we first call the closure function using num1(). In this case, we get outputs 1, 2, and 3.
Again, we call it using num2(). In this case, the value of the number variable doesn't start
from 3; instead, it starts from 1 again.
This shows that the closure returned from displayNumbers() is isolated from one another.
169

Go Packages

In this tutorial, you will learn to create, import and use Go packages in a program with the help
of examples.

A package is a container that contains various functions to perform specific tasks. For example,
the math package includes the Sqrt() function to perform the square root of a number.
While working on big projects, we have to deal with a large amount of code, and writing
everything together in the same file will make our code look messy. Instead, we can separate
our code into multiple files by keeping the related code together in packages.

Now, we can use the package whenever we need it in our projects. This way we can also reuse
our code.

Golang main() package

Remember this Hello World program, you wrote while starting with Go programming.

package main

import "fmt"

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

Here, we have started our program with the package main.


Every Go program starts with the main package. Whenever the compiler sees the main
package, it treats the program as the executable code.

Import package in Golang

In our previous example, we have used the code


170

import "fmt"

Here, we have used the import keyword to import the fmt package.
Once we import the package, we can use all of its functions in our program. For example,

package main

// import the fmt package


import "fmt"

func main() {

// use the Println() function of fmt


fmt.Println("Hello World!")
}

In the above program, we have imported the fmt package in our program. Notice the code

fmt.Println("Hello World!")

Here, we are using the Println() function of the fmt package to print the text.

Commonly used packages in Go

Now that we know how to import packages, let's learn about some of the popular packages:

• fmt Package
• math Package
• string Package

Golang fmt Package


171

In Go, the fmt package provides functions to format our input/output data. For example,
the fmt.Println() function prints the data to the output screen.
Some of the commonly used fmt functions:
Functions Descriptions

Print() prints the text to output screen

Println() prints the text to output with a new line character at the end

Printf() prints the formatted string to the output screen

Scan() get input values from the user

Scanf() get input values using the format specifier

Scanln() get input values until the new line is detected

To use these functions, we must import the fmt package.

Example 1: Golang fmt package

package main
import "fmt"

func main() {

var number int

// take input value


fmt.Scan(&number)

// print using Println


172

fmt.Println("Number is", number)

fmt.Print("Using Print")
fmt.Println("Using Println")

Output

Number is 10
Using PrintUsing Println

In the above example, we have used the fmt.Scan() function to take input value and assign it to
the number variable. We then print the value of number using the fmt.Println().
The Println() function adds a newline character at the end by default. That's why the next
statement, fmt.Print() prints the text, Using Print in the new line.
However, Print() doesn't add the newline character by default, the next print statement prints
the text Using Println in the same line

Example 2: fmt Scanf() and Printf() functions

package main
import "fmt"

func main() {

var number int

fmt.Scanf("%d", &number) // Input: 10


fmt.Printf("%d", number) // Output: 10

In the above example, functions

• fmt.Scanf("%d", &number) - takes integer input value and assign it to


the number variable
173

• fmt.Printf("%d", number) - replaces the %d format specifier by the value of number and
prints it

math package in Go

The math package provides various functions to perform mathematical operations. For
example, math.Sqrt() finds the square root of a number.
Some of the commonly used math functions:
Functions Descriptions

Sqrt() returns the square root of the number

Cbrt() returns the cube root of the number

Max() returns the larger number between two

Min() returns the smaller number between two

Mod() computes the remainder after division

To use these functions, we must import the math package.

Example: math Package

package main
import "fmt"

// import the math package


import "math"
174

func main() {

// find the square root


fmt.Println(math.Sqrt(25)) // 5

// find the cube root


fmt.Println(math.Cbrt(27)) // 3

// find the maximum number


fmt.Println(math.Max(21, 18)) // 21

// find the minimum number


fmt.Println(math.Min(21, 18)) // 18

// find the remainder


fmt.Println(math.Mod(5, 2)) // 1

Here, we have imported the math package in our program. This is why we are able to use math-
based functions like Sqrt(), Max(), etc in our program.
Note: In our example, you might have noticed that we have used two import statements to
import the fmt and math packages. In such cases, we can import both packages together using
a single import statement. For example,

// use two import statements


import "fmt"
import "math"

// use single import statement


import (
"fmt"
"math"
)

Go strings package
175

The strings package provides functions to perform operations on UTF-8 encoded strings. For
example, strings.Contains() checks if the string contains a substring.
Some of the commonly used strings functions:
Functions Descriptions

Compare() checks if two strings are equal

Contains() checks if the string contains a substring

Count() counts the number of times a substring present in the string

Join() creates a new string by concatenating elements of a string array

ToLower() converts the string to lowercase

ToUpper() converts the string to uppercase

To use these functions, we must import the strings package.

Example: string Package

package main

// import multiple packages


import (
"fmt"
"strings"
)

func main() {

// convert the string to lowercase


176

lower := strings.ToLower("GOLANG STRINGS")


fmt.Println(lower)

// convert the string to uppercase


upper := strings.ToUpper("golang strings")
fmt.Println(upper)

// create a string array


stringArray := []string{"I love", "Go Programming"}

// join elements of array with space in between


joinedString := strings.Join(stringArray, " ");
fmt.Println(joinedString)

Output

golang strings
GOLANG STRINGS
I love Go Programming

In the above example, we have used functions of the strings package to perform various
operations on the strings.

Go Custom Package

So far, we have been using packages that are already defined inside the Go library. However,
Go programming allows us to create our own custom packages and use them just like the
predefined packages.

1. Create Custom Package


To create a custom package, we first need to create a new file and declare the package. For
example,

// declare package
177

package calculator

Now, we can create functions inside the file. For example,

package calculator

// create add function


func Add(n1, n2 int) int {
return n1 + n2
}

// create subtract function


func Subtract(n1, n2 int) int {
return n1 - n2
}

In the above example, we have created a custom package named calculator. Inside the
package, we have defined two functions: Add() and Subtract().

Note: This file doesn't contain the main package. Hence, the Go compiler doesn't consider this
as an executable program and it is created for the sole purpose of sharing and reusing.

2. Importing Custom Package


Now, we can import the custom package in our main file.

package main

// import the custom package calculator


import (
"fmt"
"Packages/calculator"
)

func main() {

number1 := 9
number2 := 5

// use the add function of calculator package


fmt.Println(calculator.Add(number1, number2))

// use the subtract function of calculator package


178

fmt.Println(calculator.Subtract(number1, number2))

Here, we have successfully imported the calculator package in our program and used its
functions.

Note: We have used Packages/calculator as the name of the package. This is because the
calculator package is present inside the Packages folder and we are providing the path to that
package from the location of the main file.

How to use name aliasing with Go packages?


Sometimes the package name can be lengthy to use. In such cases, we can use aliasing and use
different names for the package. For example,

import str "strings"

Here, we are using the alias str for the strings package. Now, we can use str with strings
functions. Let's see an example.

package main

import (
"fmt"
str "strings"
)

func main() {

fmt.Println(str.ToUpper("programiz")) // PROGRAMIZ
fmt.Println(str.ToLower("PROGRAMIZ")) // programiz

Here, we are able to use the ToUpper() and ToLower() functions using the alias str.
What happens if we import a package but didn't use it in our program?
There might be times when we import packages beforehand but never use them throughout
the program. For example,

package main
179

import (
"fmt"
"math"
)

func main() {

// throws an error
fmt.Println("Programiz Go Package")

When we run this code, we will get the error message "package imported but not used". This is
because here, we have imported the math package but never used it.
To solve this issue, we can use the blank identifier, _. The blank identifier tells the compiler to
ignore the error if the package is not used. For example,

package main

import (
"fmt"
_ "math"
)

func main() {

// runs without any error


fmt.Println("Programiz Go Package")

Output

Programiz Go Package

Go Pointers

In this tutorial, we will learn about the pointer variables in Golang with the help of examples.

Pointers in Go programming allows us to directly work with memory addresses. For example,
we can access and modify the values of variables in the memory using pointers.

Before we learn about pointers, let's first understand memory addresses in Golang.
180

Memory Address

When we create a variable, a memory address is allocated for the variable to store the value.

In Go, we can access the memory address using the & operator. For example,

// Program to illustrate how memory address works

package main
import "fmt"

func main() {

var num int = 5


// prints the value stored in variable
fmt.Println("Variable Value:", num)

// prints the address of the variable


fmt.Println("Memory Address:", &num)

Output

Variable Value: 5
Memory Address: 0xc000018030

In the above example, we have created the num variable with the value 5. Notice the print
statement

fmt.Println("Memory Address:", &num)

Here, &num accesses the memory address where the num variable is stored.

Go Pointer Variables
181

In Go, we use the pointer variables to store the memory address. For example,

var num int = 5

// create the pointer variable


var ptr *int = &num

Here, we have created the pointer variable named ptr that stores the memory address of
the num variable.
*int represents that the pointer variable is of int type (stores the memory address
of int variable).
We can also create pointer variables of other types. For example,

// pointer variable of string type


var ptr1 *string

// pointer variable of double type


var ptr2 * float32

Let's now see a working example of pointers.

Example: Pointer Variables

We can assign the memory address of a variable to a pointer variable. For example,

// Program to assign memory address to pointer

package main
import "fmt"

func main() {

var name = "John"


var ptr *string

// assign the memory address of name to the pointer


ptr = &name
182

fmt.Println("Value of pointer is", ptr)


fmt.Println("Address of the variable", &name)

Output

Value of pointer is 0xc00007c1c0


Address of the variable 0xc00007c1c0

In the above example, we have created a pointer variable named ptr of type string. Here, both
the pointer variable and the address of the name variables are the same.
This is because the pointer ptr stores the memory address of the name variable.

ptr = &name

Get Value Pointed by Pointers in Golang

We use the * operator to access the value present in the memory address pointed by the
pointer. For example,

// Program to get the value pointed by a pointer

package main
import "fmt"

func main() {

var name = "John"


var ptr *string

ptr = &name

// * to get the value pointed by ptr


fmt.Println(*ptr) // John
183

Here, we have used the *ptr to access the value stored in the memory address pointed by the
pointer.
Since the pointer stores the memory address of the name variable, we get the value "John" as
output.
Note: In the above example, ptr is a pointer, not *ptr. You cannot and should not do something
like *ptr = &name
The * is called the dereference operator (when working with pointers). It operates on a pointer
and gives the value stored in that pointer.

Example: Working of Pointers in Golang

package main
import "fmt"

func main() {
var num int
var ptr *int

num = 22
fmt.Println("Address of num:",&num)
fmt.Println("Value of num:",num)

ptr = &num
fmt.Println("\nAddress of pointer ptr:",ptr)
fmt.Println("Content of pointer ptr:",*ptr)

num = 11
fmt.Println("\nAddress of pointer ptr:",ptr)
fmt.Println("Content of pointer ptr:",*ptr)

*ptr = 2
fmt.Println("\nAddress of num:",&num)
fmt.Println("Value of num:",num)
}
184

Output

Address of num: 0xc000090020


Value of num: 22

Address of pointer ptr: 0xc000090020


Content of pointer ptr: 22

Address of pointer ptr: 0xc000090020


Content of pointer ptr: 11

Address of num: 0xc000090020


Value of num: 2

Explanation: Working of Go Pointers

1. Declare Variables

var num int


var ptr *int

The pointer variable and normal variable are


declared
185

Here, we have created an integer type pointer variable ptr and a normal variable num. The two
variables are not initialized initially, so the pointer ptr doesn't point to any address.
2. Assign a value to a regular variable

num = 22

Assign a value to a regular


variable

This assigns 22 to the variable num. That is, 22 is stored in the memory location of the
variable num.
3. Assign an address to the pointer

ptr = &num
186

Assign address of a variable to


the pointer

This assigns the address of variable num to the pointer ptr.


4. Change the value of a variable

num = 11

Change the value of the


variable

This assigns 11 to the variable num.


5. Change the value using pointer
187

*ptr = 2

Change the value of the


variable using pointer

This changes the value at the memory location pointed by the pointer ptr to 2.
Nil Pointers in Golang
When we declare a pointer variable but do not initialize it, the value of the pointer is always nil.
For example,

// Program to illustrate the nil pointers

package main
import "fmt"

func main() {
// declare a pointer variable
var ptr *int

fmt.Println("Value of pointer:", ptr)

Output

Value of pointer: <nil>


188

Here, the pointer ptr is not initialized, so it does not point to any address. Hence, the default
value of a pointer is always nil.

Create Pointers using Golang new()


We can also create pointers in Go using the new() function. For example,

// Program to create pointer using new() function

package main
import "fmt"

func main() {

// create a pointer using new()


var ptr = new(int)

*ptr = 20

fmt.Println(ptr) // 0xc000016058
fmt.Println(*ptr) // 20

Here, in the line var ptr = new(int), the variable ptr becomes a pointer of type int.
When we assign *ptr to 20, the value of ptr at the memory location becomes 20.
Create pointers without using the * operator
In Go, we can also create a pointer variable without using the * operator. For example,

package main
import "fmt"

func main() {

var name = "John"

// create pointer without *


var ptr = &name

fmt.Println("Value of ptr:", ptr)


fmt.Println("Address of name:", &name)

Output
189

Value of ptr: 0xc0000101e0


Address of name: 0xc0000101e0

Here, we have directly assigned the &name (address of name) to the ptr variable.
In this case, the variable is a pointer variable, although we haven't used the * operator.

Go Pointers and Functions

In this tutorial, you will learn to use pointers and functions together in Go programming with
the help of examples.

Go pointers store the memory addresses of variables. And just like regular variables, we can
also pass pointers to functions.

Before you learn how to use pointers with functions, make sure to know about

• Go Pointers
• Functions in Golang

Pointer as Function Argument in Golang

In Go, we can pass pointers as arguments to a function. For example,

// Program to pass pointer as a function argument

package main
import "fmt"

// function definition with a pointer argument


func update(num *int) {

// dereference the pointer


*num = 30

func main() {
190

var number = 55

// function call
update(&number)

fmt.Println("The number is", number)

Output

The number is 30

In the above example, we have passed the address of number to the update() function. The
pointer num accepts this argument in the function definition.

func update(num *int) {


...
}

When we change *num to 30 inside the update() function, the value of number inside
the main() function is also changed.
This is because num and number are referring to the same address in the memory. So, updating
one updates the other as well.

Return Pointers From Function

Just like regular variables, we can also return pointers from a function. For example,

// Program to return a pointer from a function

package main
import "fmt"

func main() {

// function call
191

result := display()
fmt.Println("Welcome to", *result)

func display() *string {

message := "Programiz"

// returns the address of message


return &message

Output

Welcome to Programiz

In the above example, we have created a function named display() that returns a pointer.

func display() *string

Here, *string indicates that the function returns a pointer of string type.
Notice the return &message statement in the display() function:

func display() *string {


...
return &message
}

This indicates that the function returns the address of the message variable to
the main() function.
The returned address is assigned to the result pointer. To get the value stored in the memory
address, we have used the code *result.

Call By Reference

While passing pointers to a function, we are actually passing a reference (address) of the
variable. Instead of working with the actual value, we are working with references like
192

• accessing value using reference

• changing value using reference

That's why this process of calling a function with pointers is called call by reference in Go.
Let's see an example.

// Program to illustrate call by reference

package main
import "fmt"

// call by value
func callByValue(num int) {

num = 30
fmt.Println( num) // 30

// call by reference
func callByReference(num *int) {

*num = 10
fmt.Println(*num) // 10

func main() {

var number int

// passing value
callByValue(number)

// passing a reference (address)


callByReference(&number)

Here, we have created two functions: callByValue() and callByReference().


193

In the callByValue() function, we are directly passing the number variable. Whereas
in callByReference(), we are passing the memory address of number.

Go Pointers to Structs

In this tutorial, you will learn to use pointers and struct together in Go programming with the
help of examples.

The struct types store the variables of different data types and we use the struct variable to
access the members of the struct.

In Go, we can also create a pointer variable of struct type.

Before you learn about pointers to struct, make sure to know about:

• Go Pointers
• Go Struct

Go Pointer to Struct

Suppose we have a struct like this

type Person struct {


name string
age int
}

Now, let's create a struct variable of Person type.

person1 := Person{"John", 25}

Similar to this, we can also create a pointer variable of struct type.

var ptr *Person

We can now assign the address of the struct variable to this pointer variable. Let's see an
example.
194

package main
import "fmt"

func main() {

// declare a struct Person


type Person struct {
name string
age int
}

// instance of the struct Person


person1 := Person{"John", 25}

// create a struct type pointer that


// stores the address of person1
var ptr *Person
ptr = &person1

// print struct instance


fmt.Println(person1)

// print the struct type pointer


fmt.Println(ptr)

Output

{John 25}
&{John 25}

In the above example, we have created a struct variable person1 that initialized the struct
members; name to John and age to 25.
We have also created a pointer variable of the struct type that stores the address of person1.

var ptr *Person


ptr = &person1

Since the ptr now stores the address of person1, we get &{John 25} as the output while
printing ptr.
195

Note: We can also create struct-type pointers and assign variable addresses in the same line.
For example,

var ptr = &person1

Access struct using pointer in Golang

We can also access the individual member of a struct using the pointer. For example,

// Program to access the field of a struct using pointer

package main
import "fmt"

func main() {

// declare a struct Person


type Person struct {
name string
age int
}

person := Person{"John", 25}

// create a struct type pointer that


// stores the address of person
var ptr *Person
ptr = &person

// access the name member


fmt.Println("Name:", ptr.name)

// access the age member


fmt.Println("Age:", ptr.age)

}
196

Output

Name: John
Age: 25

In the above example, we have used the struct type pointer to access struct members:

• ptr.name - gives the value of the name member


• ptr.age - gives the value of the age member
Here, we have used the dot operator to access the struct members using the pointer.

Note: We can also use the dereference operator, * to access the members of struct. For
example,

fmt.Println(ptr.name) // John
fmt.Println((*ptr).name) // John

Change the Struct member in Go

Similarly, we can also use the pointer variable and the dot operator to change the value of a
struct member. For example,

// Program to change the struct member using pointer

package main
import "fmt"

// create struct
type Weather struct{
city string
temperature int
}

func main() {

// create struct variable


weather := Weather{"California", 20}
fmt.Println("Initial Weather:", weather)
197

// create struct type pointer


ptr := &weather

// change value of temperature to 25


ptr.temperature = 25

fmt.Println("Updated Weather:", weather)

Output

Initial Weather: {California 20}


Updated Weather: {California 25}

In the above example, notice the line

ptr.temperature = 25

Here, we have changed the value of the struct member temperature to 25 using the pointer
variable ptr.

Go Interface

In this tutorial, you will learn about the interface and its implementation in Go programming
with the help of examples.

In Go programming, we use interfaces to store a set of methods without implementation. That


is, methods of interface won't have a method body. For example,

type Shape interface {


area() float32
perimeter() float32
}

Here, Shape is an interface with methods: area() and perimeter(). You can see both methods
only have method signatures without any implementation.
198

Implementation of a Go Interface

You might be wondering what is the use of interface if the methods inside it don't have any
implementations.

Well, to use an interface, we first need to implement it by a type (struct). To implement an


interface, a struct should provide implementations for all methods of an interface. For example,

package main
import "fmt"

// interface
type Shape interface {
area() float32
}

// struct to implement interface


type Rectangle struct {
length, breadth float32
}

// use struct to implement area() of interface


func (r Rectangle) area() float32 {
return r.length * r.breadth
}

// access method of the interface


func calculate(s Shape) {
fmt.Println("Area:", s.area())
}

// main function
func main() {

// assigns value to struct members


rect := Rectangle{7, 4}

// call calculate() with struct variable rect


calculate(rect)

}
199

Output

Area: 28

Let's see how this program works:

Working on Interface Implementation


In the above example, we have created an interface named Shape with a method area(). Here,
we are trying to implement this interface by the Rectangle struct.

type Rectangle struct {


length, breadth float32
}

Now, to implement the interface, we have provided the implementation for getArea() of the
interface.

func (r Rectangle) area() float32 {


return r.length * r.breadth
}

To access this method, we have created a calculate() method

// access method of the interface


func calculate(s Shape) {
fmt.Println("Area: ", s.area())
}

Here, the method takes a variable of Shape named s and uses it to call the area() method.
Since the structure implements the interface, we have called calculate() using the variable of
structure

rect := Rectangle{7, 4}
calculate(rect)

Implement Go Interface by Multiple Structs

In Go, more than 1 struct can also implement a single interface. For example,
200

package main
import "fmt"

// interface
type Shape interface {
area() float32
}

// Rectangle struct implements the interface


type Rectangle struct {
length, breadth float32
}

// Rectangle provides implementation for area()


func (r Rectangle) area() float32 {
return r.length * r.breadth
}

// Triangle struct implements the interface


type Triangle struct {
base, height float32
}

// Triangle provides implementation for area()


func (t Triangle) area() float32 {
return 0.5 * t.base * t.height
}

// access method of the interface


func calculate(s Shape) float32 {
return s.area()
}

// main function
func main() {

// assigns value to struct members


r := Rectangle{7, 4}
t := Triangle{8, 12}

// call calculate() with struct variable rect


rectangleArea := calculate(r)
201

fmt.Println("Area of Rectangle:", rectangleArea)

triangleArea := calculate(t)
fmt.Println("Area of Triangle:", triangleArea)

Output

Area of Rectangle: 28
Area of Rectangle: 48

In the above example, we have used two structs: Rectangle and Triangle to implement the
interface Shape.
Just like before, both structs provide implementation for the area() method.
Here, this time calculate() calls the area() using interface Shape and returns it.
So, for the first call, calculate(r), the method will call the area() method implementation
of Rectangle. Similarly, for calculate(t), the method will call the area() method implementation
of Triangle.

What happens if the struct doesn't implement all methods of interface?

When a struct implements an interface, it should provide an implementation for all the
methods of the interface. If it fails to implement any method, we will get an error. For example,

package main
import "fmt"

// interface
type Shape interface {
area() float32
perimeter() float32
}

// Rectangle struct implements the interface


type Rectangle struct {
length, breadth float32
}
202

// Rectangle provides implementation for area()


func (r Rectangle) area() float32 {
return r.length * r.breadth
}

// access method of the interface


func calculate(s Shape) float32 {
return s.area()
}

// main function
func main() {

// assigns value to struct members


r := Rectangle{7, 4}

// call calculate() with struct variable rect


rectangleArea := calculate(r)
fmt.Println("Area of Rectangle:", rectangleArea)
}

Output

cannot use r (type Rectangle) as type Shape in argument to calculate:


Rectangle does not implement Shape (missing perimeter method)

In the above example, the Shape interface has two methods: area() and perimeter(). Here, we
are trying to implement the interface by the Rectangle struct.
However, the struct only provides an implementation for the area(). Since the struct doesn't
implement all the methods of the interface, we get an error.

Go Empty Interface

In this tutorial, you will learn about empty interfaces in Go programming with the help of
examples.

We know that interfaces are used to store a set of methods without implementation. In Go, we
can also create interfaces without any methods, known as empty interfaces. For example,

interface {}
203

Here, we have created an empty interface without any methods.

Variable of Empty Interface in Golang

In Go, we can create variables of the empty interface type. For example,

package main
import "fmt"

func main() {

// variable of empty interface type


var a interface {}
fmt.Println("Value:", a)

Output

Value: <nil>

Here, we have created a variable of type empty interface. When we print the variable, we
get nil as output.

Empty Interface to Pass Function Argument of Any Type

Normally in functions, when we pass values to the function parameters, we need to specify the
data type of parameters in a function definition.

However, with an empty interface, we can pass parameters of any data type. For example,

package main
import "fmt"

// empty interface as function parameter


204

func displayValue(i interface {}) {


fmt.Println(i)
}

func main() {

a := "Welcome to Programiz"
b := 20
c := false

// pass string to the function


displayValue(a)

// pass integer number to the function


displayValue(b)

// pass boolean value to the function


displayValue(c)

Output

Welcome to Programiz
20
false

In the above example, we have used an empty interface i as the parameter to


the displayValue() function.
Now the same function works for any type of parameters (string,numeric, boolean).

Go Empty Interface to Pass Any Numbers of Arguments

We can also use an empty interface to pass any number of arguments to the function
definition. For example,

package main
import "fmt"
205

// function with an empty interface as its parameter


func displayValue(i... interface {}) {
fmt.Println(i)
}

func main() {

a := "Welcome to Programiz"
b := 20
c := false

// function call with a single parameter


displayValue(a)

// function call with 2 parameters


displayValue(a, b)

// function call with 3 parameters


displayValue(a, b, c)

Output

[Welcome to Programiz 20 false 20 40 Hi again]

In the above example, we have used an empty interface i as the parameter to


the displayValue() function.

func displayValue(i... interface{})

Now the same function works for any number of parameters.

Golang Type Assertions

In this tutorial, you will learn about type assertions and their uses with the help of examples.

Type assertions allow us to access the data and data type of values stored by the interface.

Before we learn about type assertions, let's see why we need type assertions in Go.

We know that an empty interface can accept any type and number of values. For example,
206

// create an empty interface


var a interface {}

// store value of string type


a = "Hello World"

// store value of integer type


a = 10

Here, the a variable is of empty interface type, and it is storing both the string and integer
value. To learn more about empty interfaces, visit Go Empty Interface.
This seems like an important feature of an empty interface. However, sometimes this will
create ambiguity on what data an interface is holding.

To remove this ambiguity, we use type assertions.

Example: Go Type Assertions

package main
import "fmt"

func main() {

// create an empty interface


var a interface {}

// store integer to an empty interface


a = 10

// type assertion
interfaceValue := a.(int)

fmt.Println(interfaceValue)
}

Output
207

10

In the above example, we have stored the integer value 10 to the empty interface denoted
by a. Notice the code,

interfaceValue := a.(int)

Here, (int) checks if the value of a is an integer or not. If true, the value will be assigned
to interfaceValue.
Otherwise, the program panics and terminates. For example,

package main
import "fmt"

func main() {

// create an empty interface


var a interface{}

// store integer to an empty interface


a = "Golang"

// type assertion
interfaceValue := a.(int)

fmt.Println(interfaceValue)
}

Output

panic: interface conversion: interface {} is string, not int

Here, the value of the interface is a string. So, a.(int) is not true. Hence, the program panics and
terminates.
To learn more about panic, visit Go panic Statement.

Avoiding panic in Type Assertions in Go


208

In Go, the type assertion statement actually returns a boolean value along with the interface
value. For example,

var a interface {}

a = 12
interfaceValue := a.(int)

Here, the data type of value 12 matches with the specified type (int), so this code assigns the
value of a to interfaceValue.
Along with this, a.(int) also returns a boolean value which we can store in another variable. For
example,

package main
import "fmt"

func main() {

// create an empty interface


var a interface{}
a = 12

// type assertion
interfaceValue, booleanValue := a.(int)

fmt.Println("Interface Value:", interfaceValue)


fmt.Println("Boolean Value:", booleanValue)

Output

Interface Value: 12
Boolean Value: true

Here, you can see we get both the data and boolean value.

We can use this to avoid panic if the data type doesn't match the specified type.

This is because, when the type doesn't match, it returns false as the boolean value, so the panic
doesn't occur. For example,
209

package main
import "fmt"

func main() {

// create an empty interface


var a interface{}
a = "Golang"

// type assertion
interfaceValue, booleanValue := a.(int)

fmt.Println("Interface Value:", interfaceValue)


fmt.Println("Boolean Value:", booleanValue)

Output

Interface Value: 0
Boolean Value: false

Here, you can see we get 0 and false as output because the data type of value (string) doesn't
match with the specified type (int).

Go Errors

In this tutorial, you will learn about error handling in Go programming with the help of
examples.

In programming, there will be situations where our program won't run properly and generate
an error. For example,

package main
import "fmt"

func main() {

for i := 0; i < 5; i++ {


result := 20 / i
210

fmt.Println(result)
}
}

When we run this code, we will get an error called integer divide by zero.
During the first iteration, the value of i is 0, so the code result := 20 / i is trying to divide a
number by 0.
In this state, the program stops its execution known as a Go error. Here, "integer divide by
zero" is an error message returned by the compiler.

Note: The error we get in our previous example is a built-in error. In Go, we can also create our
own errors for efficient programming.

Golang Error Handling

When an error occurs, the execution of a program stops completely with a built-in error
message. In Go, we . Hence, it is important to handle those exceptions in our program.

Unlike other programming languages, we don't use try/catch to handle errors in Go. We can
handle errors using:
• New() Function
• Errof() Function

1. Go Error using New() Function

In Go, we can use the New() function to handle an error. This function is defined inside
the errors package and allows us to create our own error message.
Let's see an example,

package main

// import the errors package


211

import (
"errors"
"fmt"
)

func main() {

message := "Hello"

// create error using New() function


myError := errors.New("WRONG MESSAGE")

if message != "Programiz" {
fmt.Println(myError)
}

Output

WRONG MESSAGE

In the above example, we have created an error using the errors.New() function.

myError := errors.New("WRONG MESSAGE")

Here, the "WRONG MESSAGE" inside the New() function is the custom error message. It prints
when the message variable does not match with the given string "PROGRAMIZ".

Example: Error using New()

package main

// import the errors package


import (
"errors"
"fmt"
)
212

// function that checks if name is Programiz


func checkName(name string) error {

// create a new error


newError := errors.New("Invalid Name")

// return the error if name is not Programiz


if name != "Programiz" {
return newError
}

// return nil if there is no error


return nil
}

func main() {

name := "Hello"

// call the function


err := checkName(name)

// check if the err is nil or not


if err != nil {
fmt.Println(err)
} else {
fmt.Println("Valid Name")
}

Output

Invalid Name

In the above example, we have created a function named checkName()

checkName(name string) error {...}

The return of this function is an error, which means this function will return a value of error
type
213

Inside the function, we have created an error using the New() function. Here, if the name is
not Programiz, we are returning the newly created error message.
However, if the name is Programiz, we are returning nil (represents no error).
Inside the main() function, we have called the checkName() function using
err := checkName(name)
Here, the returned error will be assigned to err. We then checked if the value in err is nil or not.

2. Error using Errorf() in Golang

We can also handle Go errors using the Errorf() function. Unlike, New(), we can format the
error message using Errorf().
This function is present inside the fmt package, so we can directly use this if we have imported
the fmt package.
Let's see an example.

package main
import "fmt"

func main() {

age := -14

// create an error using Efforf()


error := fmt.Errorf("%d is negative\nAge can't be negative", age)

if age < 0 {
fmt.Println(error)
} else {
fmt.Println("Age: %d", age);
}
}

Output

-14 is negative
214

Age can't be negative

In the above example, we have used the Errorf() function to create a new formatted error.

error := fmt.Errorf("%d is negative\nAge can't be negative", age)

Here, you can see we have used the format specifier %d to use the value of age inside our
error.

Example: Error using Errorf()

package main
import "fmt"

func divide(num1, num2 int) error {

// returns error
if num2 == 0 {
return fmt.Errorf("%d / %d\nCannot Divide a Number by zero", num1, num2)
}

// returns the result of division


return nil
}

func main() {

err := divide(4,0)

// error found
if err != nil {
fmt.Printf("error: %s", err)

// error not found


} else {
fmt.Println("Valid Division")
}
}
215

Output

error: 4 / 0
Cannot Divide a Number by zero

In the above example, we have created a function named divide().

func divide(num1, num2 int) error {...}

The return of this function is an error, which means this function will return an error value.
Inside the function, we have created a formatted error using the Errorf(). If the
condition num2==0 is true, the function divide returns the error message inside the Errorf().
However, if num2 is not 0, we are returning nil, which represents that there is no error.

Custom Errors in Golang

In Go, we can create custom errors by implementing an error interface in a struct.


error Interface

type error interface {


Error() string
}

Here, the Error() method returns an error message in string form if there is an error. Otherwise,
it returns nil.
Now, to create a custom error, we have to implement the Error() method on a Go struct.
Let's see an example,

package main

import "fmt"

type DivisionByZero struct {


message string
}

// define Error() method on the struct


func (z DivisionByZero) Error() string {
216

return "Number Cannot Be Divided by Zero"


}

func divide(n1 int, n2 int) (int, error) {

if n2 == 0 {
return 0, &DivisionByZero{}
} else {
return n1 / n2, nil
}
}

func main() {

number1 := 15
// change the value of number2 to get different result
number2 := 0

result, err := divide(number1, number2)

// check if error occur or not


if err != nil {
fmt.Println(err)
} else {
fmt.Printf("Result: %d", result)
}
}

Output

Number Cannot Be Divided by Zero

In the above example, we are implementing the Error() method of the error interface on
the DivisionByZero struct.

func (z DivisionByZero) Error() string {


return "Number Cannot Be Divided by Zero"
}

Here,

• z DivisionByZero - an instance of the DivisionByZero struct


• string - return type of the method
217

• "Number Cannot Be Divided by Zero" - error message


We have then created a divide() method that takes two parameters and returns the result and
an error.

func divide(n1 int, n2 int) (int, error) {...}

The function returns 0 and &DivisionByZero{}, if the value of n2 is 0. Here, &DivisionByZero{} is


an instance of the struct. To learn more, visit Go Pointers to Struct.
Inside the main() function, if the returned error type is not nil, we print the error message.
Note that we are not calling the Error() method from anywhere in the program, but we can
access its return value using the struct instance.

Go defer, panic and recover

In this tutorial, we will learn about the error handling statements defer, panic, and recover in
Golang with the help of examples.

In Go, we use defer, panic and recover statements to handle errors.

We use defer to delay the execution of functions that might cause an error.
The panic statement terminates the program immediately and recover is used to recover the
message during panic.
Before we learn about error handling statements, make sure to know about Go errors.

defer in Go

We use the defer statement to prevent the execution of a function until all other functions
execute. For example,

package main
import "fmt"

func main() {

// defer the execution of Println() function


defer fmt.Println("Three")
218

fmt.Println("One")
fmt.Println("Two")

Output

One
Two
Three

In the above example, we have used the defer before the first print statement.

That's why the Println() function is executed last after all other functions are executed.

Multiple defer Statements in Go

When we use multiple defer in a program, the order of execution of the defer statements will
be LIFO (Last In First Out).
This means the last defer statement will be executed first. For example,

package main
import "fmt"

func main() {

defer fmt.Println("One")
defer fmt.Println("Two")
defer fmt.Println("Three")

Output

Three
Two
219

One

In the above example, we are calling the Println() function using 3 defer statements.
As you can see, the order of execution is LIFO. That is, the last defer statement is executed first,
and the first defer statement is executed last

Golang panic

We use the panic statement to immediately end the execution of the program. If our program
reaches a point where it cannot be recovered due to some major errors, it's best to use panic.

The lines of code after the panic statement are not executed. For example,

package main
import "fmt"

func main() {

fmt.Println("Help! Something bad is happening.")


panic ("Ending the program")

fmt.Println("Waiting to execute")

Output

Help! Something bad is happening.


panic: Ending the program

Here, the program is terminated when it reaches the panic statement. That's why the print
statement after the panic is not executed.

Note: panic: in the output specifies that the program is terminated due to panic and it's the
panic message.
220

Example: Panic in Golang

package main

import "fmt"

func division(num1, num2 int) {

// if num2 is 0, program is terminated due to panic


if num2 == 0 {
panic("Cannot divide a number by zero")

} else {
result := num1 / num2
fmt.Println("Result: ", result)
}
}

func main() {

division(4, 2)
division(8, 0)
division(2, 8)

Output

Result: 2
panic: Cannot divide a number by zero

In the above example, we have created a function that performs the division of two
numbers: num1 and num2.
Inside the function, we have used an if...else statement that checks if num2 (denominator)
is 0 or not. If it is 0, the execution of the program stops because of the panic statement.

panic("Cannot divide a number by zero")


221

Here, when we run the program, we first get result 2 (division of 4 and 2). However, during the
second function call, the value of num2 is 0 (division of 8 and 0).
Hence, the execution of the program is terminated.

recover in Go Programming

The panic statement immediately terminates the program. However, sometimes it might be
important for a program to complete its execution and get some required results.

In such cases, we use the recover statement to handle panic in Go. The recover
statement prevents the termination of the program and recovers the program from panic.
Let's see an example.

package main
import "fmt"

// recover function to handle panic


func handlePanic() {

// detect if panic occurs or not


a := recover()

if a != nil {
fmt.Println("RECOVER", a)
}

func division(num1, num2 int) {

// execute the handlePanic even after panic occurs


defer handlePanic()

// if num2 is 0, program is terminated due to panic


if num2 == 0 {
panic("Cannot divide a number by zero")
} else {
222

result := num1 / num2


fmt.Println("Result: ", result)
}
}

func main() {

division(4, 2)
division(8, 0)
division(2, 8)

Output

Result: 2
RECOVER Cannot divide a number by zero
Result: 0

In the above example, we have created a handlePanic() function to recover from the panicking
state.

func handlePanic() {

// detect if panic occurs or not


a := recover()

if a != nil {
fmt.Println("RECOVER", a)
}
}

Here, we have used a := recover() to detect any occurrence of panic in our program and assign
the panic message to a.
In our example, a panic occurs, so there will be some value in a. Hence, the if statement is
executed, which prints the panic message.
Inside the division() function, we are calling the handlePanic() function

defer handlePanic()

Here, notice two things:


223

• We are calling the handlePanic() before the occurrence of panic. It's because the
program will be terminated if it encounters panic and we want to execute handlePanic() before
the termination.
• We are using defer to call handlePanic(). It's because we only want to handle the panic
after it occurs, so we are deferring its execution.

Goroutines

In this tutorial, you'll learn about goroutines to create concurrent program in Go with the help
of examples.

In Go, we use goroutines to create concurrent programs. Concurrent programs are able to run
multiple processes at the same time.

Suppose we have a program that has two independent functions. In normal programs, two
functions will be executed synchronously. That is, the second function is executed only after the
execution of the first function.

However, since both functions are independent, it would be efficient if we could execute both
functions together asynchronously.

For this, we use goroutines that help us to achieve concurrency in programming.

Create Goroutine

We can convert a regular function to a goroutine by calling the function using the go keyword.
For example,

func display() {
// code inside the function
}

// start goroutine
go display()

Here, display() is a goroutine.


224

Example: Goroutine

Let's now see a working example of concurrent programming using goroutine.

package main
import (
"fmt"
"time"
)

// create a function
func display(message string) {

fmt.Println(message)
}

func main() {

// call goroutine
go display("Process 1")

display("Process 2")
}

Output

Process 2

In the above example, we have called the display() function two times:
• go display("Process 1") - as a goroutine
• display("Process 2") - regular function call
During the normal execution, the control of the program moves to the function during the first
function call and once the execution is completed, it returns back to the next statement.

In our example, the next statement is the second call to the function. So, first Process 1 should
be printed and then Process 2.
However, we are only getting Process 2 as output.
225

This is because we have used go with the first function call, so it is treated as a goroutine. And
the function runs independently and the main() function now runs concurrently.
Hence, the second call is executed immediately and the program terminates without
completing the first function call.

Working of Goroutine

Run two functions concurrently using Goroutine

In a concurrent program, the main() is always a default goroutine. Other goroutines can not
execute if the main() is not executing.
So, in order to make sure that all the goroutines are executed before the main function ends,
we sleep the process so that the other processes get a chance to execute.
226

// Program to run two goroutines concurrently

package main
import (
"fmt"
"time"
)

// create a function
func display(message string) {

// infinite for loop


for {
fmt.Println(message)

// to sleep the process for 1 second


time.Sleep(time.Second * 1)
}
}

func main() {

// call function with goroutine


go display("Process 1")

display("Process 2")

Output

Process 3
Process 2
Process 1

In the above example, we have added a line in the function definition.

time.Sleep(time.Second * 1)

Here, when the display("Process 2") is executing, the time.Sleep() function stops the process
for 1 second. In that 1 second, the goroutine go display("Process 1") is executed.
227

This way, the functions run concurrently before the main() functions stops.

Multiple Goroutines

While running multiple Goroutines together, they interact with each other concurrently. The
order of execution of goroutine is random, so we might not get the output as expected. For
example,

// Program to illustrate multiple goroutines

package main

import (
"fmt"
"time"
)

func display(message string) {

fmt.Println(message)

func main() {

// run two different goroutine


go display("Process 1")
go display("Process 2")
go display("Process 3")

// to sleep main goroutine for 1 sec


time.Sleep(time.Second * 1)
}

Output

Process 1
Process 1
.
228

.
Process 3
Process 2
Process 2
.
.

Here, all the goroutines run concurrently with the sleep time of 1 second. The order of
execution is random, so everytime we run the program, we get a different output.

Benefits of Goroutines

Here are some of the major benefits of goroutines.

• With Goroutines, concurrency is achieved in Go programming. It helps two or more


independent functions to run together.

• Goroutines can be used to run background operations in a program.

• It communicates through private channels so the communication between them is


safer.

• With goroutines, we can split one task into different segments to perform better.

Go Channel

In this tutorial, you will learn about Go Channel and its operations with the help of examples.

Channels in Go act as a medium for goroutines to communicate with each other.

We know that goroutines are used to create concurrent programs. Concurrent programs can
run multiple processes at the same time.

However, sometimes there might be situations where two or more goroutines need to
communicate with one another. In such situations, we use channels that allow goroutines to
communicate and share resources with each other.

Before you learn about channels, make sure to understand how Goroutines work in Go.
229

Create Channel in Go

In Go, we use the make() function to create a channel. For example,

channelName := make(chan int)

Here,

• channelName - name of the channel


• (chan int) - indicates that the channel is of integer type

Example: Go Channel

package main
import "fmt"

func main() {

// create channel of integer type


number := make(chan int)

// access type and value of channel


fmt.Printf("Channel Type: %T\n", number)
fmt.Printf("Channel Value: %v", number)

Output

Channel Type: chan int


Channel Value: 0xc00007a060

In the above example, we have used the make() function to create a channel named number.
Here, we have used format specifiers:
• %T - to print the type of the channel
230

• %v - to print the value of the channel


Since the channel is of integer type (specified by chan int), we get the same output.
Also, the value of a channel is a memory address, which acts as a medium through which
goroutines send and receive data to communicate.

Golang Channel Operations

Once we create a channel, we can send and receive data between different goroutines through
the channel.

1. Send data to the channel


The syntax to send data to the channel is

channelName <- data

Here the data after the <- operator is sent to channelName.


Let's see some examples,

// send integer data to channel


number <- 15

// send string data


message <- "Learning Go Channel"

2. Receive data from the channel


The syntax to receive data from the channel is:

<- channelName

This accesses the data from channelName.


Let's see some example,

// receive data 15
<- number

// receive data "Learning Go Channel"


231

<- message

Example: Go Channel Operations

package main
import "fmt"

func main() {

// create channel
number := make(chan int)
message := make(chan string)

// function call with goroutine


go channelData(number, message)

// retrieve channel data


fmt.Println("Channel Data:", <-number)
fmt.Println("Channel Data:", <-message)

func channelData(number chan int, message chan string) {

// send data into channel


number <- 15
message <- "Learning Go channel"

Output

Channel Data: 15
Channel Data: Learning Go Channel

In the above example, we have created two channels named number and message.
232

Here, we have used the <- operator to perform operations to send and receive data from the
channel.

Blocking Nature of Channel

In Go, the channel automatically blocks the send and receive operations depending on the
status of goroutines.

1. When a goroutine sends data into a channel, the operation is blocked until the data is
received by another goroutine. For example,

package main
import "fmt"

func main() {

// create channel
ch := make(chan string)

// function call with goroutine


go sendData(ch)

// receive channel data


fmt.Println(<-ch)

func sendData(ch chan string) {

// data sent to the channel


ch <- "Received. Send Operation Successful"

fmt.Println("No receiver! Send Operation Blocked")

Output
233

No receiver! Send Operation Blocked


Received. Send Operation Successful

In the above example, we have created the sendData() goroutine to send data to the channel.
The goroutine sends the string data to the channel.
If the channel is not ready to receive the message, it prints "No receiver! Send Operation
Blocked".
Inside the main() function, we are calling sendData() before receiving data from the channel.
That's why the first "No receiver..." is printed.
And, when the channel is ready to receive data, the data sent by goroutine is printed.

2. When a goroutine receives data from a channel, the operation is blocked until another
goroutine sends the data to the channel. For example,

package main
import "fmt"

func main() {

// create channel
ch := make(chan string)

// function call with goroutine


go receiveData(ch)

fmt.Println("No data. Receive Operation Blocked")

// send data to the channel


ch <- "Data Received. Receive Operation Successful"

func receiveData(ch chan string) {

// receive data from the channel


fmt.Println(<-ch)
234

Output

No data. Receive Operation Blocked


Data Received. Receive Operation Successful

In the above example, we have created the receiveData() goroutine to receive data from the
channel. The goroutine receives the string data from the channel.
If the channel hasn't yet sent the data, it prints "No data. Receive Operation Blocked".
Inside the main() function, we are calling receiveData() before sending data to the channel.
That's why the first "No data..." is printed.
And, when the channel sends data, the data received by goroutine is printed.

Go select

In this tutorial, you will learn about the Golang select statement with the help of examples.

The select statement in Go allows us to execute a channel among many alternatives.

Before you learn about select, make sure you understand Go Channel.
Syntax of Select Statement

select {

case firstChannel:

case secondChannel:

case thirdChannel:

Here, each case of the select represents an individual channel. And, based on the availability of
channel operations, the select statement executes a channel.

Note: The syntax of select case looks similar to that of the Switch Case in Go. And, like the
switch case, only one of the cases is executed by select.
235

Example: Golang select Statement

package main
import "fmt"

func main() {

// create two channels


number := make(chan int)
message := make(chan string)

// function call with goroutine


go channelNumber(number)
go channelMessage(message)

// selects and executes a channel


select {

case firstChannel := <- number:


fmt.Println("Channel Data:", firstChannel)

case secondChannel := <- message:


fmt.Println("Channel Data:", secondChannel)
}

// goroutine to send integer data to channel


func channelNumber(number chan int) {
number <- 15
}

// goroutine to send string data to channel


func channelMessage(message chan string) {
message <- "Learning Go select"
}

Output
236

Channel Data: Learning Go select

In the above example, we have created two channels number and message. Here, we have
used the goroutines
• channelNumber() to send data to the number channel
• channelMessage() to send data to the message channel
The program includes two different channels, so we have used the select statement to execute
one of the channels among the two.

select {

case firstChannel := <- number:


fmt.Println("Channel Data:", firstChannel)

case secondChannel := <- message:


fmt.Println("Channel Data:", secondChannel)
}

Here, the case firstChannel gets the value from the number channel and prints it. Similarly, the
case secondChannel gets the value from the message channel and prints it.
When you run this program, you might get different outputs. In our example, both channels are
ready for execution, so the select statement executes the channel randomly.

Go select with one Channel Ready for Execution

We know that when both multiple channels are ready for execution, the select statement
executes the channel randomly.

However, if only one of the channels is ready for execution, it executes that channel. For
example,

package main
import (
"fmt"
"time"
)
237

func main() {

// create channels
number := make(chan int)
message := make(chan string)

// function call with goroutine


go channelNumber(number)
go channelMessage(message)

// selects and executes a channel


select {
case firstChannel := <-number:
fmt.Println("Channel Data:", firstChannel)

case secondChannel := <-message:


fmt.Println("Channel Data:", secondChannel)
}

// goroutine to send data to the channel


func channelNumber(number chan int) {
number <- 15
}

// goroutine to send data to the channel


func channelMessage(message chan string) {

// sleeps the process by 2 seconds


time.Sleep(2 * time.Second)

message <- "Learning Go Select"


}

Output

Channel Data: 15

In the above example, we have created two goroutines,


238

• channelNumber() - sends data to the number channel


• channelMessage() - sends data to the message channel
Inside the channelMessage() goroutine, we have used the time.Sleep() method to make
the message channel unavailable for execution.
Now, for the first 2 seconds, only the number channel is ready for execution. That's why the
select statement executes the case firstChannel (number channel).

Go select to block Channels

The select statement blocks all channels if they are not ready for execution. Suppose, in our
previous example, if both the number and message channels are not ready for execution, select
blocks both the channels for a certain time until one is available for execution.

Let's see an example.

package main
import (
"fmt"
"time"
)

func main() {

// create channels
number := make(chan int)
message := make(chan string)

// function call with goroutine


go channelNumber(number)
go channelMessage(message)

// selects and executes a channel


select {
case firstChannel := <-number:
fmt.Println("Channel Data:", firstChannel)

case secondChannel := <-message:


239

fmt.Println("Channel Data:", secondChannel)


}

// goroutine to send data to the channel


func channelNumber(number chan int) {

// sleeps the process for 2 seconds


time.Sleep(2 * time.Second)

number <- 15
}

// goroutine to send data to the channel


func channelMessage(message chan string) {

// sleeps the process by 2 seconds


time.Sleep(2 * time.Second)

message <- "Learning Go Select"


}

Output

Channel Data: Learning Go Select

In the above example, we have used time.Sleep() method to make both the channels
unavailable for execution for 2 seconds.
Now, the select statement will block both channels for the first 2 seconds. That's why we won't
get any output for 2 seconds.
Then, it executes one of the channels randomly because both channels will be available
after 2 seconds.

Golang select with the default case


240

When none of the channels are ready, the select blocks the program. However, it's better to
display some messages instead of blocking until the channels are ready.

For this, we use the default case, which is executed if none of the channels are ready for
execution. For example,

package main

import (
"fmt"
"time"
)

func main() {

// create channels
number := make(chan int)
message := make(chan string)

// function call with goroutine


go channelNumber(number)
go channelMessage(message)

// selects and executes a channel


select {
case firstChannel := <-number:
fmt.Println("Channel Data:", firstChannel)

case secondChannel := <-message:


fmt.Println("Channel Data:", secondChannel)

// default case
default:
fmt.Println("Wait!! Channels are not ready for execution")

// goroutine to send data to the channel


func channelNumber(number chan int) {
241

// sleeps the process for 2 seconds


time.Sleep(2 * time.Second)

number <- 15
}

// goroutine to send data to the channel


func channelMessage(message chan string) {

// sleeps the process by 2 seconds


time.Sleep(2 * time.Second)

message <- "Learning Go Select"


}

Output

Wait!! Channels are not ready for execution

In the above example, we have used the default case with select that prints "Wait!! Channels
are not ready for execution" if both the channels are not ready.
Since both channels sleep for 2 seconds, they won't be available for execution for the first.
That's why the statement of default case is executed.
After 2 seconds, both channels will be ready for execution, and one of them will be executed by
select.

Go struct

In this tutorial, you will learn about the struct type in Go programming with the help of
examples.

A struct is used to store variables of different data types. For example,

Suppose we want to store the name and age of a person. We can create two variables: name
and age and store value.

However, suppose we want to store the same information of multiple people.


242

In this case, creating variables for a person might be a tedious task. We can create a struct that
stores the name and age to overcome this.

And, we can use this same struct for every person.

Declare Go Struct

The syntax to declare a struct in Go is:

type StructureName struct {


// structure definition
}

Here,

1. struct - keyword used to define a structure


2. StructName - the name of the structure
Let's see an example,

type Person struct {


name string
age int
}

Here, we have declared a struct named Person. Inside the curly braces {}, the struct contains
two variables name and age.

Struct instances

A struct definition is just a blueprint. To use a struct, we need to create an instance of it. For
example,

type Person struct {


name string
243

age int
}

// create an instance of struct


var person1 Person

Here, we have created an instance person1 followed by the name of the struct Person.
Now, we can use the person1 instance to access and define the struct properties.

// define the value of name and age


person1 = Person("John", 25)

We can also directly define a struct while creating an instance of the struct. For example,

person1 := Person("John", 25)

Here, John will be assigned to the name variable and 25 will be assigned to the age variable of
the Person struct.

Example: Golang struct

package main
import "fmt"

func main() {

// declare a struct
type Person struct {
name string
age int
}

// assign value to struct while creating an instance


person1 := Person{ "John", 25}

fmt.Println(person1)

// define an instance
244

var person2 Person

// assign value to struct variables


person2 = Person {
name: "Sara",
age: 29,
}

fmt.Println(person2)
}

Output

{John 25}
{Sara 29}

Access a struct in Golang

We can access individual elements of a struct using the struct instances. For example,

// Program to access the individual elements of struct

package main
import "fmt"

func main() {

// declare a struct
type Rectangle struct {
length int
breadth int
}

// declare instance rect1 and defining the struct


rect := Rectangle{22, 12}

// access the length of the struct


245

fmt.Println("Length:", rect.length)

// access the breadth of the struct


fmt.Println("Breadth:", rect.breadth)

area := rect.length * rect.breadth


fmt.Println("Area:", area)

Output

Length: 22
Breadth: 12
Area: 264

Here, we have used the . (dot) symbol to access the property of a struct.
• rect.length - access the value of the length variable from the struct
• rect.breadth - access the value of the breadth variable from the struct

Function inside a Struct in Go

Go also allows us to create a function inside a struct. It treats function as a field of struct. For
example,

// Program to use function as a field of struct

package main
import "fmt"

// initialize the function Rectangle


type Rectangle func(int, int) int

// create structure
type rectanglePara struct {
length int
246

breadth int
color string

// function as a field of struct


rect Rectangle

func main() {

// assign values to struct variables


result := rectanglePara{
length: 10,
breadth: 20,
color: "Red",
rect: func(length int, breadth int) int {
return length * breadth
},

fmt.Println("Color of Rectangle: ", result.color)


fmt.Println("Area of Rectangle: ", result.rect(result.length, result.breadth))

Output

Color of Rectangle: Red


Area of Rectangle: 200

In the above example, we have defined a function Rectangle as a field of


struct rectanglePara and used the function to find the area of a rectangle.

Go Variable Scope

In this tutorial, you'll learn about local and global variables in Golang with the help of examples.

In Go, we can declare variables in two different scopes: local scope and global scope.

A variable scope specifies the region where we can access a variable. For example,
247

func addNumbers() {
sum := 5 + 4
}

Here, the sum variable is created inside the function, so it can only be accessed within it (local
scope). This type of variable is called a local variable.
Based on the scope, we can classify Go variables into two types:

• Local Variables

• Global Variables

Go Local Variables

When we declare variables inside a function, these variables will have a local scope (within the
function). We cannot access them outside the function.

These types of variables are called local variables. For example,

// Program to illustrate local variables

package main
import "fmt"

func addNumbers() {

// local variables
var sum int

sum = 5 + 9

func main() {

addNumbers()
248

// cannot access sum out of its local scope


fmt.Println("Sum is", sum)

Output

undefined: sum

Here, the sum variable is local to the addNumbers() function, so it can only be accessed within
the function.
That's why we get an error when we try to access the function from main().
To fix this issue, we can either return the value of the local variable and assign it to another
variable inside the main function. Or we can make the variable sum global.

Global Variables in Golang

When we declare variables before the main() function, these variables will have global scope.
We can access them from any part of the program.
These types of variables are called global variables. For example,

// Program to illustrate global variable

package main
import "fmt"

// declare global variable before main function


var sum int

func addNumbers () {

// local variable
sum = 9 + 5
}
249

func main() {

addNumbers()

// can access sum


fmt.Println("Sum is", sum)

Output

Sum is 14

This time we can access the sum variable from inside the main() function. This is because we
have created the sum variable as the global variable.

// outside the function


var sum int

Now, the sum will be accessible from any scope (region) of the program.
What are the default values of local variables and global variables?
When we declare local and global variables without assigning any values to them, they are
assigned to their default values.

In Go, the default values of int and float32 types are 0.

// Program to illustrate the default values of global and local variables

package main
import "fmt"

// global variable
var variable1 int

func defaultValues() {

// local variable
var variable2 float32

fmt.Println(variable1) // 0
fmt.Println(variable2) // 0
250

func main() {
defaultValues()
}

In the above example, we have initialized local and global variables. Regardless of where it's
initialized, the default values of both int and float32 are 0.
What happens if both local and global variables have the same name?
If we have local and global variables with the same variable names, the compiler gives priority
to the local variable. For example,

// Program to illustrate the priorities of variables

package main
import "fmt"

// define global variable


var random = "Global"

func main() {

// define local variable with same name


var random = "Local"

fmt.Println(random)

Output

Local

Here, both the local and global variables have common name random. When we print random,
it prints "Local", not "Global". That means the compiler is giving priority to the local variable
over the global variable.
Why is local variables preferred over global variables?
In some scenarios, the use of global variables is considered bad practice. It is because a global
variable can be accessed from any part of the program.
251

So, when one function changes the value of a global variable, other functions of the same
program might not know about the changed value. This way it might create inconsistency in the
value of global variables.

Let's see an example.

// Program to find the temperature

package main
import "fmt"

// global variable

var temperature float32 = 35

func findTemp1() {
temperature = 43
}

func findTemp2() {
temperature = 29
}

func main() {
fmt.Println("Initial Value:", temperature)
findTemp1()
fmt.Println("Value after findTemp1():", temperature)
findTemp2()
fmt.Println("Value after findTemp2():", temperature)
}

Output

Initial Value: 35
Value after findTemp1(): 43
Value after findTemp2(): 29

Here, we have created 2 functions to find the temperature. When the findTemp2() function
changes the value of temperature, findTemp1 might not know about the change.
So, findTemp1() assumes the value is the same as it had defined and keeps functioning
according to that value.
This can result in unexpected output and creates high confusion in larger programs.

You might also like