Intro To Go
Intro To Go
Intro To Go
In this tutorial, you will learn how to get started with Go programming and write our first Go
program.
• 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.
To get familiar with the basic syntax of Go programming, let's write our first program.
package main
import "fmt"
func main() {
2
fmt.Println("Hello World!")
}
Output
Hello World!
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.
package main
fun main() {
}
3
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.
• Data Scraping.
• built-in testing
• efficient execution
• efficient compilation
• ease of programming
• 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.
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.
Here,
Method 1
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.
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.
1. If a variable is not assigned any value, a default value is assigned to it. For example,
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.
Example: Go Variables
package main
import "fmt"
func main() {
Output
10
20
30
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
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"
In Go, it's also possible to declare multiple variables at once by separating them with commas.
For example,
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:
• 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.
1a a age
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,
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,
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
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
• 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.
Note: Unless we have a specific requirement, we usually use the int keyword to create integers.
11
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
The float type is used to hold values with decimal points. For example, 6.7, -34.2
Note: If we define float variables without specifying size explicitly, the size of the variable will
be 64 bits. For example,
package main
import "fmt"
func main() {
var salary1 float32
var salary2 float64
salary1 = 50000.503882901
fmt.Println(salary1)
fmt.Println(salary2)
Output
50000.504
50000.503882901
13
package main
import "fmt"
func main() {
var message string
message = "Welcome to Programiz"
fmt.Println(message)
Output
Welcome to Programiz
The boolean data type has one of two possible values either true or false.
Keyword: bool
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.
• 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()
package main
func main() {
fmt.Print("Hello, ")
fmt.Print("World!")
Output
Hello World!
Here, the fmt.Print() function prints the content inside parentheses ().
16
Print Variables
package main
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.
We can print multiple values and variables at once by separating them with commas. For
example,
package main
17
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.
package main
import "fmt"
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
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.
integer %d
float %g
string %s
bool %t
package main
import "fmt"
func main() {
var number annualSalary = 65000.5
Output
Here, fmt.Printf() converts the "Annual Salary: %g" string to "Annual Salary: 65000.5".
20
package main
import "fmt"
func main() {
var name = "John"
age := 23
Output
It's also possible to print output without using the fmt package. For that, we
use print() and println(). For example,
package main
func main() {
println("Using println instead of fmt.Println")
Output
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
Output
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
Output
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.
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
}
24
Output
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
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
Output
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
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
package main
import "fmt"
func main() {
var name string
var age int
Output
In the above example, we have used the Scanln() function to take two input values
for name and age using their respective format specifiers.
Here,
integer %d
float %g
string %s
bool %t
package main
import "fmt"
func main() {
var temperature float32
var sunny bool
Output
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, we use two forward slashes // to create a single-line comment. For example,
package main
import "fmt"
func main() {
// declare a variable
age := 25
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,
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
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.
package main
import "fmt"
func main() {
age := 25
height := 170
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
Output
Age is 25
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.
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.
Go Operators
In this tutorial, you will learn about different operators in Go programming with the help of
examples.
• Arithmetic operators
• Assignment operator
• Relational operators
• Logical operators
Arithmetic Operator
33
Operators Example
+ (Addition) a+b
- (Subtraction) a-b
* (Multiplication) a*b
/ (Division) a/b
package main
import "fmt"
func main() {
num1 := 6
num2 := 2
Output
6+2=8
6-2=4
6 * 2 = 12
package main
import "fmt"
func main() {
num1 := 11
num2 := 4
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.
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
Output
11 / 4 = 2.75
36
package main
import "fmt"
func main() {
num1 := 11
num2 := 4
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
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
Go Assignment Operators
var number = 34
Here, the = operator assigns the value on right (34) to the variable on left (number).
package main
import "fmt"
func main() {
num := 6
var result int
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.
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.
We use the relational operators to compare two values or variables. For example,
5 == 6
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
More on Go Operators
If we use multiple operators together in a single statement, which operator is executed first?
For example,
package main
import "fmt"
func main() {
num := 212
for i := 0; i <= 3; i++ {
}
}
Output
For example,
package main
import "fmt"
func main() {
num := 212
for i := 0; i <= 3; i++ {
43
}
}
Output
package main
import "fmt"
func main() {
num := 20
// 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
// 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,
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
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:
package main
import "fmt"
func main() {
Output
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.
package main
46
import "fmt"
func main() {
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.
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() {
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:
package main
import "fmt"
func main() {
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,
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.
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.
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() {
Output:
We use the relational operators to compare two values or variables. For example,
number1 := 9
number2 := 3
49
package main
import "fmt"
func main() {
number1 := 12
number2 := 20
var result bool
// equal to operator
result = (number1 == number2)
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
package main
import "fmt"
func main() {
number1 := 6
number2 := 12
number3 := 6
var result bool
Output
Go Boolean Expression
In programming, expressions that return boolean values: true or false are known as boolean
expressions. For example,
number1 := 5
number2 := 8
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.
Go if statement
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
package main
import "fmt"
func main() {
number := 15
Output
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
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
}
package main
import "fmt"
func main() {
number := 10
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
number := -5
-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,
package main
import "fmt"
func main() {
number1 := 12
number2 := 20
if number1 == number2 {
59
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
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)
}
Output
Result: 12 < 20
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 in Go
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.
If we need to execute other cases after the matching case, we can use fallthrough inside the
case statement. For example,
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
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.
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:
In Go, the expression in switch is optional. If we don't use the expression, the switch statement
is true by default. For example,
package main
import "fmt"
func main() {
numberOfDays := 28
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.
In Golang, we can also use an optional statement along with the expression. The statement and
expression are separated by semicolons. For example,
package main
67
import "fmt"
func main() {
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.
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.
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.
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.
package main
import "fmt"
func main() {
Output
1
2
3
70
4
5
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.
package main
import "fmt"
func main() {
var n, sum = 10, 0
Output
sum = 55
package main
import "fmt"
func main() {
// create an array
numbers := [5] int {11, 22, 33, 44, 55}
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.
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,
package main
import "fmt"
func main() {
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.
package main
import "fmt"
func main() {
package main
import "fmt"
func main() {
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
}
package main
import ("fmt")
func main() {
number := 1
Output
1
2
3
4
5
package main
import ("fmt")
func main() {
multiplier := 1
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,
package main
import "fmt"
func main(){
number := 1
fmt.Printf("%d\n", number);
number ++
}
}
Output
1
2
3
4
5
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.
We can use the for range loop to access the individual index and element of an array. For
example,
package main
79
import "fmt"
func main() {
// array of numbers
numbers := [5]int{21, 24, 27, 30, 33}
Output
numbers[0] = 21
numbers[1] = 24
numbers[2] = 27
numbers[3] = 30
numbers[4] = 33
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,
package main
import "fmt"
func main() {
string := "Golang"
fmt.Println("Index: Character")
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.
In Go, we can also use the for range keyword with map to access key-value pairs. For example,
package main
import "fmt"
81
func main() {
// create a map
subjectMarks := map[string]float32{"Java": 80, "Python": 81, "Golang": 85}
fmt.Println("Marks obtained:")
Output
Marks Obtained:
Java: 80
Python: 81
Golang: 85
In every iteration, the loop iterates through the key-value pair of a map.
1 Java 80
2 Python 81
3 Golang 85
We can also use the for range to only access the keys of a map. For example,
82
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.
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,
Here, irrespective of the condition of the for loop, the break statement terminates the loop.
83
Working of break
statement with for loop in Golang
package main
import "fmt"
func main() {
for i := 1 ; i <= 5 ; i++ {
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.
When we use the break statement with nested loops, it terminates the inner loop. For example,
package main
import "fmt"
func main() {
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,
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 continue
statement with for loop in Golang
package main
import "fmt"
func main() {
for i := 1 ; i <= 5 ; i++ {
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.
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++ {
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.
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, the size represents the length of an array. The list of elements of the array goes inside {}.
For example,
package main
import "fmt"
func main() {
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
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,
package main
import "fmt"
func main() {
languages := [3]string{"Go", "Java", "C++"}
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.
package main
import "fmt"
func main() {
// declare an array
var arrayOfIntegers[3] int
92
fmt.Println(arrayOfIntegers)
}
Output
[5 10 15]
package main
import "fmt"
func main() {
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
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"}
fmt.Println(weather)
}
Output
Here, we have reassigned a new value to index 2 to change the array element
from "Cloudy" to "Stromy".
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
Output
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}
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
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,
package main
import "fmt"
func main() {
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
Go Slice
In this tutorial, you will learn about the Go slice and its various operations with the help of
examples.
However, unlike arrays, slice doesn't have a fixed size. We can add or remove elements from
the array.
numbers := []int{1, 2, 3, 4, 5}
Here,
// this is an array
numbers := [5]int{1, 2, 3, 4, 5}
// this is a slice
numbers := []int{1, 2, 3, 4, 5}
package main
import "fmt"
func main() {
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,
In Go programming, we can also create a slice from an existing array. For example,
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].
package main
import "fmt"
func main() {
// an integer array
numbers := [8]int{10, 20, 30, 40, 50, 60, 70, 80}
fmt.Println(sliceNumbers)
Output
99
Slice Functions
In Go, slice provides various built-in functions that allow us to perform different operations on a
slice.
Functions Descriptions
package main
import "fmt"
func main() {
primeNumbers := []int{2, 3}
100
Output
Prime Numbers: [2 3 5 7]
primeNumbers = append(primeNumbers, 5, 7)
package main
import "fmt"
func main() {
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
We can use the copy() function to copy elements of one slice to another. For example,
package main
import "fmt"
func main() {
// print numbers
fmt.Println("Numbers:", numbers)
}
Output
Numbers: [2 3 5]
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.
We use the len() function to find the number of elements present inside the slice. For example,
package main
import "fmt"
func main() {
fmt.Println("Length:", numbers)
Output
Length: 5
In Go, we can use a for loop to iterate through a slice. For example,
package main
import "fmt"
func main() {
numbers := []int{2, 4, 6, 8, 10}
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,
package main
import "fmt"
func main() {
Output
Go
104
C++
[Go Java C++]
Note: The slice index always starts with 0. Hence, the first element of a slice is present at
index 0, not 1
package main
import "fmt"
func main() {
weather := []string{"Rainy", "Sunny", "Cloudy"}
fmt.Println(weather)
}
Output
105
numbers := make([]int, 5, 7)
package main
import "fmt"
func main() {
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,
package main
import "fmt"
func main() {
numbers := []int{2, 4, 6, 8, 10}
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:
package main
import "fmt"
func main() {
// create a map
subjectMarks := map[string]float32{"Golang": 85, "Java": 80, "Python": 81}
fmt.Println(subjectMarks)
}
Output
Note: We can also create a map using var keyword. For example,
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"}
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)
Output
In the above example, we have changed the value of a map by re-assigning the key "US" with a
new value "Washington DC"
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)
Output
• 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
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)
Output
Here, we have used the delete() function to remove the element denoted by the key "John".
delete(personAge, "John")
Note: If the key passed to the delete() function is not present inside the map, the function does
nothing.
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}
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.
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.
package main
import "fmt"
func main() {
fmt.Println(student)
}
Output
Once we create a map with the make() function, we can now perform all other operations
(change, delete, access) to the map.
package main
import "fmt"
func main() {
113
// create a map
places := map[string]string{"Nepal": "Kathmandu", "US": "Washington DC", "Norway": "Oslo"}
Output
Nepal
US
Norway
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"}
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.
Go struct
In this tutorial, you will learn about the struct type in Go programming with the help of
examples.
Suppose we want to store the name and age of a person. We can create two variables: name
and age and store value.
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.
Declare Go Struct
// structure definition
}
Here,
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,
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.
We can also directly define a struct while creating an instance of the struct. For example,
116
Here, John will be assigned to the name variable and 25 will be assigned to the age variable of
the Person struct.
package main
import "fmt"
func main() {
// declare a struct
type Person struct {
name string
age int
}
fmt.Println(person1)
// define an instance
var person2 Person
fmt.Println(person2)
}
Output
117
{John 25}
{Sara 29}
We can access individual elements of a struct using the struct instances. For example,
package main
import "fmt"
func main() {
// declare a struct
type Rectangle struct {
length int
breadth int
}
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
Go also allows us to create a function inside a struct. It treats function as a field of struct. For
example,
package main
import "fmt"
// create structure
type rectanglePara struct {
length int
breadth int
color string
func main() {
color: "Red",
rect: func(length int, breadth int) int {
return length * breadth
},
Output
Go String
In this tutorial, you will learn about the Go String and its various operations with the help of
examples.
// using var
var name1 = "Go Programming"
Here, both name1 and name2 are strings with the value "Go Programming".
package main
import "fmt"
func main() {
fmt.Println(message1)
fmt.Println(message2)
}
Output
Hello,
Welcome to Programiz
In Go, we can also represent strings using the tick mark notation. For example,
package main
import "fmt"
func main() {
fmt.Println(message)
}
Output
I love Go Programming
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,
package main
import "fmt"
func main() {
Hence,
In Go, we use the len() function to find the length of a string. For example,
package main
import "fmt"
func main() {
// create string
message := "Welcome to Programiz"
stringLength := len(message)
Output
Here, len() returns the number of characters present inside the string.
In Go, we can use the + operator to join (concatenates) strings together. For example,
package main
import "fmt"
func main() {
message1 := "I love"
message2 := "Go programming"
fmt.Println(result)
Output
I love Go programming
Here, we have used the + operator to join three strings: message1, " ", and message2.
124
In Go, the strings package provides various methods that can be used to perform different
operations on strings.
Functions Descriptions
To use these methods, we must first import the strings package in our code.
import (
"fmt"
"strings"
)
We use the Compare() of the strings package to compare two strings. For example,
125
package main
import (
"fmt"
"strings"
)
func main() {
// compare strings
fmt.Println(strings.Compare(string1, string2)) // -1
fmt.Println(strings.Compare(string2, string3)) // 1
fmt.Println(strings.Compare(string1, string3)) // 0
strings.Compare(string1, string2)
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,
package main
import (
"fmt"
"strings"
)
func main() {
fmt.Println(result)
fmt.Println(result)
}
Output
true
false
• 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,
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)
Output
Here,
// replace 2 r with 2 a
strings.Replace("Programiz", "r", "R", 2)
// Output: PRogRamiz
package main
import (
"fmt"
"strings"
)
func main() {
// convert to uppercase
text1 = strings.ToUpper(text1)
fmt.Println(text1)
// convert to lowercase
text2 = strings.ToLower(text2)
fmt.Println(text2)
129
Output
GO IS FUN TO LEARN
i love 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"
fmt.Println(splittedString)
}
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
•
•
Create Strings from a Slice
We use escape characters to escape some of the characters present inside a string. For
example,
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,
Now, the escape characters tell the compiler to escape double quotes and read the whole text.
package main
import "fmt"
func main() {
fmt.Println(message)
}
Note: \n and \t are other popular escape sequences that add a new line and tab inside a string.
In Go, strings are immutable. This means once we create a string, we cannot change it.
// 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.
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,
package main
import "fmt"
func main() {
// create 2 strings
string1 := "Programiz"
string2 := "programiz"
fmt.Println(result)
}
// Output: false
Note: The == operator is case sensitive. Hence, Programiz and programiz are not equal.
package main
import (
"fmt"
"strings"
)
func main() {
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,
package main
import "fmt"
func main() {
text := "Golang"
Output
G
o
l
a
n
g
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 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
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.
package main
import "fmt"
// define a function
func greet() {
fmt.Println("Good Morning")
}
func main() {
135
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()
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
package main
import "fmt"
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
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.
// 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.
package main
import "fmt"
sum := n1 + n2
fmt.Println("Sum:", sum)
}
func main() {
Output
Sum: 34
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.
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, 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)
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
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
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.
In Go, we can also return multiple values from a function. For example,
package main
import "fmt"
// function definition
func calculate(n1 int, n2 int) (int, int) {
sum := n1 + n2
difference := n1 - n2
func main() {
// function call
sum, difference := calculate(21, 13)
Output
Sum: 34 Difference: 8
...
}
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.
1. Code Reusability
We can reuse the same function multiple times in our program. For example,
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() {
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.
package main
import "fmt"
func addNumbers() {
// local variables
var sum int
sum = 5 + 9
func main() {
addNumbers()
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.
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,
package main
import "fmt"
func addNumbers () {
// local variable
sum = 9 + 5
}
func main() {
addNumbers()
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.
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.
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
package main
import "fmt"
func main() {
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.
package main
import "fmt"
// global variable
149
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.
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.
package main
import "fmt"
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.
In this example, we will use an if...else statement to prevent the infinite recursion.
package main
import "fmt"
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)
Recursion in Golang
package main
import "fmt"
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.
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.
package main
import "fmt"
func main() {
155
var number = 3
// function call
var result = factorial (number)
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.
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.
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
Here, we have assigned the anonymous function to the variable greet and used greet() to call
the function.
Like a regular function, an anonymous function can also accept function parameters. For
example,
package main
import "fmt"
func main() {
// 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)
Like in regular functions, we can also return a value from an anonymous function. For example,
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)
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.
package main
import "fmt"
func main() {
// anonymous function
area := func(length, breadth int) int {
return length * breadth
}
Output
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
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
func main() {
// function call
result := findSquare(sum(6, 9))
Output
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,
package main
import "fmt"
number := 10
return func() int {
number++
return number
}
}
func main() {
a := displayNumber()
fmt.Println(a())
}
162
Output
11
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.
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
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)
}
func main() {
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
package main
import "fmt"
return func() {
fmt.Println("Hi John")
}
164
func main() {
g1 := greet()
g1()
}
Output
Hi John
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.
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
func main() {
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()
fmt.Println(message())
Let's see one more example to make this concept clear for you.
package main
import "fmt"
func main() {
Output
167
3
5
7
3
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()
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"
// 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())
Output
1
2
3
1
2
In the above example, the displayNumbers() function returns an anonymous function that
increases the number by 1.
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.
Remember this Hello World program, you wrote while starting with Go programming.
package main
import "fmt"
func main() {
fmt.Println("Hello World!")
}
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
func main() {
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.
Now that we know how to import packages, let's learn about some of the popular packages:
• fmt Package
• math Package
• string Package
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
Println() prints the text to output with a new line character at the end
package main
import "fmt"
func main() {
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
package main
import "fmt"
func main() {
• 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
package main
import "fmt"
func main() {
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,
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
package main
func main() {
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.
// declare package
177
package calculator
package calculator
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.
package main
func main() {
number1 := 9
number2 := 5
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.
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() {
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,
package main
import "fmt"
func main() {
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
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,
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,
We can assign the memory address of a variable to a pointer variable. For example,
package main
import "fmt"
func main() {
Output
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
We use the * operator to access the value present in the memory address pointed by the
pointer. For example,
package main
import "fmt"
func main() {
ptr = &name
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.
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
1. Declare Variables
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
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
num = 11
*ptr = 2
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,
package main
import "fmt"
func main() {
// declare a pointer variable
var ptr *int
Output
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.
package main
import "fmt"
func main() {
*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() {
Output
189
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.
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
package main
import "fmt"
func main() {
190
var number = 55
// function call
update(&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.
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.
Just like regular variables, we can also return pointers from a function. For example,
package main
import "fmt"
func main() {
// function call
191
result := display()
fmt.Println("Welcome to", *result)
message := "Programiz"
Output
Welcome to Programiz
In the above example, we have created a function named display() that returns a pointer.
Here, *string indicates that the function returns a pointer of string type.
Notice the return &message statement in the display() function:
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
That's why this process of calling a function with pointers is called call by reference in Go.
Let's see an example.
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() {
// passing value
callByValue(number)
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.
Before you learn about pointers to struct, make sure to know about:
• Go Pointers
• Go Struct
Go Pointer to Struct
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() {
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.
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,
We can also access the individual member of a struct using the pointer. For example,
package main
import "fmt"
func main() {
}
196
Output
Name: John
Age: 25
In the above example, we have used the struct type pointer to access struct members:
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
Similarly, we can also use the pointer variable and the dot operator to change the value of a
struct member. For example,
package main
import "fmt"
// create struct
type Weather struct{
city string
temperature int
}
func main() {
Output
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.
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.
package main
import "fmt"
// interface
type Shape interface {
area() float32
}
// main function
func main() {
}
199
Output
Area: 28
Now, to implement the interface, we have provided the implementation for getArea() of the
interface.
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)
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
}
// main function
func main() {
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.
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
}
// main function
func main() {
Output
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
In Go, we can create variables of the empty interface type. For example,
package main
import "fmt"
func main() {
Output
Value: <nil>
Here, we have created a variable of type empty interface. When we print the variable, we
get nil as output.
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"
func main() {
a := "Welcome to Programiz"
b := 20
c := false
Output
Welcome to Programiz
20
false
We can also use an empty interface to pass any number of arguments to the function
definition. For example,
package main
import "fmt"
205
func main() {
a := "Welcome to Programiz"
b := 20
c := false
Output
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
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.
package main
import "fmt"
func main() {
// 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() {
// type assertion
interfaceValue := a.(int)
fmt.Println(interfaceValue)
}
Output
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.
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() {
// type assertion
interfaceValue, booleanValue := a.(int)
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() {
// type assertion
interfaceValue, booleanValue := a.(int)
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() {
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.
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
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 (
"errors"
"fmt"
)
func main() {
message := "Hello"
if message != "Programiz" {
fmt.Println(myError)
}
Output
WRONG MESSAGE
In the above example, we have created an error using the errors.New() function.
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".
package main
func main() {
name := "Hello"
Output
Invalid Name
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.
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
if age < 0 {
fmt.Println(error)
} else {
fmt.Println("Age: %d", age);
}
}
Output
-14 is negative
214
In the above example, we have used the Errorf() function to create a new formatted error.
Here, you can see we have used the format specifier %d to use the value of age inside our
error.
package main
import "fmt"
// returns error
if num2 == 0 {
return fmt.Errorf("%d / %d\nCannot Divide a Number by zero", num1, num2)
}
func main() {
err := divide(4,0)
// error found
if err != nil {
fmt.Printf("error: %s", err)
Output
error: 4 / 0
Cannot Divide a Number by zero
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.
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"
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
Output
In the above example, we are implementing the Error() method of the error interface on
the DivisionByZero struct.
Here,
In this tutorial, we will learn about the error handling statements defer, panic, and recover in
Golang with the help of examples.
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() {
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.
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("Waiting to execute")
Output
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
package main
import "fmt"
} 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.
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"
if a != nil {
fmt.Println("RECOVER", a)
}
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() {
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()
• 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.
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()
Example: 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
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
package main
import (
"fmt"
"time"
)
// create a function
func display(message string) {
func main() {
display("Process 2")
Output
Process 3
Process 2
Process 1
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,
package main
import (
"fmt"
"time"
)
fmt.Println(message)
func main() {
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
• 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.
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
Here,
Example: Go Channel
package main
import "fmt"
func main() {
Output
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
Once we create a channel, we can send and receive data between different goroutines through
the channel.
<- channelName
// receive data 15
<- number
<- message
package main
import "fmt"
func main() {
// create channel
number := make(chan int)
message := make(chan string)
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.
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)
Output
233
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)
Output
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.
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
package main
import "fmt"
func main() {
Output
236
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 {
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.
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)
Output
Channel Data: 15
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.
package main
import (
"fmt"
"time"
)
func main() {
// create channels
number := make(chan int)
message := make(chan string)
number <- 15
}
Output
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.
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)
// default case
default:
fmt.Println("Wait!! Channels are not ready for execution")
number <- 15
}
Output
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.
Suppose we want to store the name and age of a person. We can create two variables: name
and age and store value.
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.
Declare Go Struct
Here,
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,
age int
}
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.
We can also directly define a struct while creating an instance of the struct. For example,
Here, John will be assigned to the name variable and 25 will be assigned to the age variable of
the Person struct.
package main
import "fmt"
func main() {
// declare a struct
type Person struct {
name string
age int
}
fmt.Println(person1)
// define an instance
244
fmt.Println(person2)
}
Output
{John 25}
{Sara 29}
We can access individual elements of a struct using the struct instances. For example,
package main
import "fmt"
func main() {
// declare a struct
type Rectangle struct {
length int
breadth int
}
fmt.Println("Length:", rect.length)
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
Go also allows us to create a function inside a struct. It treats function as a field of struct. For
example,
package main
import "fmt"
// create structure
type rectanglePara struct {
length int
246
breadth int
color string
func main() {
Output
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.
package main
import "fmt"
func addNumbers() {
// local variables
var sum int
sum = 5 + 9
func main() {
addNumbers()
248
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.
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,
package main
import "fmt"
func addNumbers () {
// local variable
sum = 9 + 5
}
249
func main() {
addNumbers()
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.
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.
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,
package main
import "fmt"
func main() {
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.
package main
import "fmt"
// global variable
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.