Go Tutorial
Go Tutorial
Audience
This tutorial is designed for software programmers with a need to understand the
Go programming language from scratch. This tutorial will give you enough
understanding on Go programming language from where you can take yourself to
higher levels of expertise.
Prerequisites
Before proceeding with this tutorial, you should have a basic understanding of
computer programming terminologies. If you have a good command over C, then
it would be quite easy for you to understand the concepts of Go programming and
move fast on the learning track.
All the content and graphics published in this e-book are the property of Tutorials
Point (I) Pvt. Ltd. The user of this e-book is prohibited to reuse, retain, copy,
distribute or republish any contents or a part of contents of this e-book in any
manner without written consent of the publisher. We strive to update the contents
of our website and tutorials as timely and as precisely as possible, however, the
contents may contain inaccuracies or errors. Tutorials Point (I) Pvt. Ltd. provides
no guarantee regarding the accuracy, timeliness or completeness of our website
or its contents including this tutorial. If you discover any errors on our website or
in this tutorial, please notify us at contact@tutorialspoint.com.
i
Go Programming
Table of Contents
About the Tutorial ..................................................................................................................................... i
Audience .................................................................................................................................................... i
Prerequisites .............................................................................................................................................. i
1. OVERVIEW ............................................................................................................................ 1
Go Programs ............................................................................................................................................. 2
Tokens in Go ............................................................................................................................................. 8
Line Separator........................................................................................................................................... 8
Comments ................................................................................................................................................ 8
ii
Go Programming
Identifiers ................................................................................................................................................. 9
Keywords .................................................................................................................................................. 9
Whitespace in Go ...................................................................................................................................... 9
6. VARIABLES .......................................................................................................................... 14
7. CONSTANTS ........................................................................................................................ 19
8. OPERATORS ........................................................................................................................ 23
iii
Go Programming
Function Arguments................................................................................................................................ 69
Function Closures.................................................................................................................................... 74
Method ................................................................................................................................................... 75
iv
Go Programming
v
Go Programming
vi
1. OVERVIEW Go Programming
Features of Go Programming
The most important features of Go programming are listed below:
1
Go Programming
Go Programs
A Go program can vary in length from 3 lines to millions of lines and it should be
written into one or more text files with the extension ".go". For example, hello.go.
You can use "vi", "vim" or any other text editor to write your Go program into a
file.
Try the following example using the Try it option available at the top right corner
of the following sample code:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
2
2. ENVIRONMENT SETUP Go Programming
This gives you confidence in what you are reading and to check the result with
different options. Feel free to modify any example and execute it online.
Try the following example using the Try it option available at the top right corner
of the following sample code displayed on our website:
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
For most of the examples given in this tutorial, you will find a Try it option.
A text editor
Go compiler
Text Editor
You will require a text editor to type your programs. Examples of text editors
include Windows Notepad, OS Edit command, Brief, Epsilon, EMACS, and vim or
vi.
The name and version of text editors can vary on different operating systems. For
example, Notepad is used on Windows, and vim or vi is used on Windows as well
as Linux or UNIX.
3
Go Programming
The files you create with the text editor are called source files. They contain
program source code. The source files for Go programs are typically named with
the extension ".go".
Before starting your programming, make sure you have a text editor in place and
you have enough experience to write a computer program, save it in a file, compile
it, and finally execute it.
The Go Compiler
The source code written in source file is the human readable source for your
program. It needs to be compiled and turned into machine language so that your
CPU can actually execute the program as per the instructions given. The Go
programming language compiler compiles the source code into its final executable
program.
The following section explains how to install Go binary distribution on various OS.
Download Go Archive
Download the latest version of Go installable archive file from Go Downloads. The
following version is used in this tutorial: go1.4.windows-amd64.msi.
OS Archive name
Windows go1.4.windows-amd64.msi
Linux go1.4.linux-amd64.tar.gz
Mac go1.4.darwin-amd64-osx10.8.pkg
FreeBSD go1.4.freebsd-amd64.tar.gz
4
Go Programming
OS Output
Installation on Windows
Use the MSI file and follow the prompts to install the Go tools. By default, the
installer uses the Go distribution in c:\Go. The installer should set the c:\Go\bin
directory in Window's PATH environment variable. Restart any open command
prompts for the change to take effect.
File: test.go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
Output
Hello, World!
5
3. PROGRAM STRUCTURE Go Programming
Before we study the basic building blocks of Go programming language, let us first
discuss the bare minimum structure of Go programs so that we can take it as a
reference in subsequent chapters.
Package Declaration
Import Packages
Functions
Variables
Statements and Expressions
Comments
Let us look at a simple code that would print the words "Hello World!":
package main
import "fmt"
func main() {
/* This is my first sample program. */
fmt.Println("Hello, World!")
}
1. The first line of the program package main defines the package name in
which this program should lie. It is a mandatory statement, as Go programs
run in packages. The main package is the starting point to run the program.
Each package has a path and name associated with it.
2. The next line import "fmt" is a preprocessor command which tells the Go
compiler to include the files lying in the package fmt.
3. The next line func main() is the main function where the program execution
begins.
6
Go Programming
4. The next line /*...*/ is ignored by the compiler and it is there to add
comments in the program. Comments are also represented using // similar
to Java or C++ comments.
Executing a Go Program
Let us discuss how to save the source code in a file, compile it, and finally execute
the program. Please follow the steps given below:
6. If there are no errors in your code, then you will see "Hello World!" printed
on the screen.
$ go run hello.go
Hello, World!
Make sure the Go compiler is in your path and that you are running it in the
directory containing the source file hello.go.
7
4. BASIC SYNTAX Go Programming
Tokens in Go
A Go program consists of various tokens. A token is either a keyword, an identifier,
a constant, a string literal, or a symbol. For example, the following Go statement
consists of six tokens:
fmt.Println("Hello, World!")
fmt
.
Println
(
"Hello, World!"
)
Line Separator
In a Go program, the line separator key is a statement terminator. That is,
individual statements don't need a special separator like ; in C. The Go compiler
internally places ; as the statement terminator to indicate the end of one logical
entity.
fmt.Println("Hello, World!")
fmt.Println("I am in Go Programming World!")
Comments
Comments are like helping texts in your Go program and they are ignored by the
compiler. They start with /* and terminate with the characters */ as shown below:
/* my first program in Go */
8
Go Programming
You cannot have comments within comments and they do not occur within a string
or character literals.
Identifiers
A Go identifier is a name used to identify a variable, function, or any other user-
defined item. An identifier starts with a letter A to Z or a to z or an underscore _
followed by zero or more letters, underscores, and digits (0 to 9).
Keywords
The following list shows the reserved words in Go. These reserved words may not
be used as constant or variable or any other identifier names.
Whitespace in Go
Whitespace is the term used in Go to describe blanks, tabs, newline characters,
and comments. A line containing only whitespace, possibly with a comment, is
known as a blank line, and a Go compiler totally ignores it.
Whitespaces separate one part of a statement from another and enables the
compiler to identify where one element in a statement, such as int, ends and the
next element begins. Therefore, in the following statement:
9
Go Programming
There must be at least one whitespace character (usually a space) between int
and age for the compiler to be able to distinguish them. On the other hand, in the
following statement:
10
5. DATA TYPES Go Programming
Boolean types
1 They are boolean types and consists of the two predefined
constants: (a) true (b) false
Numeric types
2 They are again arithmetic types and they represents a) integer types
or b) floating point values throughout the program.
String types
A string type represents the set of string values. Its value is a
3 sequence of bytes. Strings are immutable types. That is, once they
are created, it is not possible to change the contents of a string. The
predeclared string type is string.
Derived types
They include (a) Pointer types, (b) Array types, (c) Structure types,
4
(d) Union types and (e) Function types f) Slice types g) Function
types h) Interface types i) Map types j) Channel Types
Array types and structure types are collectively referred to as aggregate types.
The type of a function specifies the set of all functions with the same parameter
and result types. We will discuss the basic types in the following section, whereas
other types will be covered in the upcoming chapters.
11
Go Programming
Integer Types
The predefined architecture-independent integer types are:
uint8
1
Unsigned 8-bit integers (0 to 255)
uint16
2
Unsigned 16-bit integers (0 to 65535)
uint32
3
Unsigned 32-bit integers (0 to 4294967295)
uint64
4
Unsigned 64-bit integers (0 to 18446744073709551615)
int8
5
Signed 8-bit integers (-128 to 127)
int16
6
Signed 16-bit integers (-32768 to 32767)
int32
7
Signed 32-bit integers (-2147483648 to 2147483647)
int64
8 Signed 64-bit integers
(-9223372036854775808 to 9223372036854775807)
Floating Types
The predefined architecture-independent float types are:
float32
1
IEEE-754 32-bit floating-point numbers
float64
2
IEEE-754 64-bit floating-point numbers
12
Go Programming
complex64
3
Complex numbers with float32 real and imaginary parts
complex128
4
Complex numbers with float64 real and imaginary parts
The value of an n-bit integer is n bits and is represented using two's complement
arithmetic operations.
byte
1
same as uint8
rune
2
same as int32
uint
3
32 or 64 bits
int
4
same size as uint
uintptr
5
an unsigned integer to store the uninterpreted bits of a pointer value
13
6. VARIABLES Go Programming
A variable is nothing but a name given to a storage area that the programs can
manipulate. Each variable in Go has a specific type, which determines the size and
layout of the variable's memory, the range of values that can be stored within that
memory, and the set of operations that can be applied to the variable.
The name of a variable can be composed of letters, digits, and the underscore
character. It must begin with either a letter or an underscore. Upper and lowercase
letters are distinct because Go is case-sensitive. Based on the basic types
explained in the previous chapter, there will be the following basic variable types:
Type Description
Variable Definition in Go
A variable definition tells the compiler where and how much storage to create for
the variable. A variable definition specifies a data type and contains a list of one
or more variables of that type as follows:
var i, j, k int;
var c, ch byte;
var f, salary float32;
d = 42;
14
Go Programming
The statement var i, j, k; declares and defines the variables i, j and k; which
instructs the compiler to create variables named i, j, and k of type int.
Variables can be initialized (assigned an initial value) in their declaration. The type
of variable is automatically judged by the compiler based on the value passed to
it. The initializer consists of an equal sign followed by a constant expression as
follows:
variable_name = value;
For example,
For definition without an initializer: variables with static storage duration are
implicitly initialized with nil (all bytes have the value 0); the initial value of all
other variables is zero value of their data type.
Example
Try the following example, where the variable has been declared with a type and
initialized inside the main function:
package main
import "fmt"
func main() {
var x float64
x = 20.0
fmt.Println(x)
fmt.Printf("x is of type %T\n", x)
}
When the above code is compiled and executed, it produces the following result:
15
Go Programming
20
x is of type float64
Example
Try the following example, where the variables have been declared without any
type. Notice, in case of type inference, we initialized the variable y
with := operator, whereas x is initialized using = operator.
package main
import "fmt"
func main() {
var x float64 = 20.0
y := 42
fmt.Println(x)
fmt.Println(y)
fmt.Printf("x is of type %T\n", x)
fmt.Printf("y is of type %T\n", y)
}
When the above code is compiled and executed, it produces the following result:
20
42
x is of type float64
y is of type int
16
Go Programming
Example
package main
import "fmt"
func main() {
var a, b, c = 3, 4, "foo"
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Printf("a is of type %T\n", a)
fmt.Printf("b is of type %T\n", b)
fmt.Printf("c is of type %T\n", c)
}
When the above code is compiled and executed, it produces the following result:
3
4
foo
a is of type int
b is of type int
c is of type string
2. rvalue: The term rvalue refers to a data value that is stored at some
address in memory. An rvalue is an expression that cannot have a value
assigned to it which means an rvalue may appear on the right- but not left-
hand side of an assignment.
17
Go Programming
Variables are lvalues and so may appear on the left-hand side of an assignment.
Numeric literals are rvalues and so may not be assigned and cannot appear on the
left-hand side.
x = 20.0
10 = 20
18
7. CONSTANTS Go Programming
Constants refer to fixed values that the program may not alter during its
execution. These fixed values are also called literals.
Constants can be of any of the basic data types like an integer constant, a floating
constant, a character constant, or a string literal. There are also enumeration
constants as well.
Constants are treated just like regular variables except that their values cannot
be modified after their definition.
Integer Literals
An integer literal can be a decimal, octal, or hexadecimal constant. A prefix
specifies the base or radix: 0x or 0X for hexadecimal, 0 for octal, and nothing for
decimal.
An integer literal can also have a suffix that is a combination of U and L, for
unsigned and long, respectively. The suffix can be uppercase or lowercase and can
be in any order.
212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */
85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */
19
Go Programming
Floating-point Literals
A floating-point literal has an integer part, a decimal point, a fractional part, and
an exponent part. You can represent floating point literals either in decimal form
or exponential form.
While representing using decimal form, you must include the decimal point, the
exponent, or both and while representing using exponential form, you must
include the integer part, the fractional part, or both. The signed exponent is
introduced by e or E.
3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */
Escape Sequence
When certain characters are preceded by a backslash, they will have a special
meaning in Go. These are known as Escape Sequence codes which are used to
represent newline (\n), tab (\t), backspace, etc. Here, you have a list of some of
such escape sequence codes:
\\ \ character
\? ? character
\a Alert or bell
\b Backspace
\f Form feed
\n Newline
\r Carriage return
20
Go Programming
\t Horizontal tab
\v Vertical tab
package main
import "fmt"
func main() {
fmt.Printf("Hello\tWorld!")
}
When the above code is compiled and executed, it produces the following result:
Hello World!
String Literals in Go
String literals or constants are enclosed in double quotes "". A string contains
characters that are similar to character literals: plain characters, escape
sequences, and universal characters.
You can break a long line into multiple lines using string literals and separating
them using whitespaces.
Here are some examples of string literals. All the three forms are identical strings.
"hello, dear"
"hello, \
dear"
21
Go Programming
package main
import "fmt"
func main() {
const LENGTH int = 10
const WIDTH int = 5
var area int
When the above code is compiled and executed, it produces the following result:
value of area : 50
22
8. OPERATORS Go Programming
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Miscellaneous Operators
This tutorial explains arithmetic, relational, logical, bitwise, assignment, and other
operators one by one.
Arithmetic Operators
Following table shows all the arithmetic operators supported by Go language.
Assume variable A holds 10 and variable B holds 20 then:
23
Go Programming
Example
Try the following example to understand all the arithmetic operators available in
Go programming language:
package main
import "fmt"
func main() {
var a int = 21
var b int = 10
var c int
c = a + b
fmt.Printf("Line 1 - Value of c is %d\n", c )
c = a - b
fmt.Printf("Line 2 - Value of c is %d\n", c )
c = a * b
fmt.Printf("Line 3 - Value of c is %d\n", c )
c = a / b
fmt.Printf("Line 4 - Value of c is %d\n", c )
c = a % b
fmt.Printf("Line 5 - Value of c is %d\n", c )
a++
fmt.Printf("Line 6 - Value of a is %d\n", a )
a--
fmt.Printf("Line 7 - Value of a is %d\n", a )
}
When you compile and execute the above program, it produces the following
result:
Line 1 - Value of c is 31
Line 2 - Value of c is 11
Line 3 - Value of c is 210
Line 4 - Value of c is 2
24
Go Programming
Line 5 - Value of c is 1
Line 6 - Value of a is 22
Line 7 - Value of a is 21
Relational Operators
The following table lists all the relational operators supported by Go language.
Assume variable A holds 10 and variable B holds 20, then:
Example
Try the following example to understand all the relational operators available in
Go programming language:
package main
import "fmt"
25
Go Programming
func main() {
var a int = 21
var b int = 10
if( a == b ) {
fmt.Printf("Line 1 - a is equal to b\n" )
} else {
fmt.Printf("Line 1 - a is not equal to b\n" )
}
if ( a < b ) {
fmt.Printf("Line 2 - a is less than b\n" )
} else {
fmt.Printf("Line 2 - a is not less than b\n" )
}
if ( a > b ) {
fmt.Printf("Line 3 - a is greater than b\n" )
} else {
fmt.Printf("Line 3 - a is not greater than b\n" )
}
/* Lets change value of a and b */
a = 5
b = 20
if ( a <= b ) {
fmt.Printf("Line 4 - a is either less than or equal to b\n" )
}
if ( b >= a ) {
fmt.Printf("Line 5 - b is either greater than or equal to b\n" )
}
}
When you compile and execute the above program, it produces the following
result:
26
Go Programming
Logical Operators
The following table lists all the logical operators supported by Go language.
Assume variable A holds 1 and variable B holds 0, then:
The following table shows all the logical operators supported by Go language.
Assume variable A holds true and variable B holds false, then:
27
Go Programming
Example
Try the following example to understand all the logical operators available in Go
programming language:
package main
import "fmt"
func main() {
var a bool = true
var b bool = false
if ( a && b ) {
fmt.Printf("Line 1 - Condition is true\n" )
}
if ( a || b ) {
fmt.Printf("Line 2 - Condition is true\n" )
}
/* lets change the value of a and b */
a = false
b = true
if ( a && b ) {
fmt.Printf("Line 3 - Condition is true\n" )
} else {
fmt.Printf("Line 3 - Condition is not true\n" )
}
if ( !(a && b) ) {
fmt.Printf("Line 4 - Condition is true\n" )
}
}
When you compile and execute the above program, it produces the following
result:
28
Go Programming
Bitwise Operators
Bitwise operators work on bits and perform bit-by-bit operation. The truth tables
for &, |, and ^ are as follows:
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
A = 0011 1100
B = 0000 1101
-----------------
~A = 1100 0011
The Bitwise operators supported by C language are listed in the following table.
Assume variable A holds 60 and variable B holds 13, then:
Binary Left Shift Operator. The left A << 2 will give 240
<<
operands value is moved left by the which is 1111 0000
29
Go Programming
Example
Try the following example to understand all the bitwise operators available in Go
programming language:
package main
import "fmt"
func main() {
c = a | b /* 61 = 0011 1101 */
fmt.Printf("Line 2 - Value of c is %d\n", c )
c = a ^ b /* 49 = 0011 0001 */
fmt.Printf("Line 3 - Value of c is %d\n", c )
30
Go Programming
When you compile and execute the above program, it produces the following
result:
Line 1 - Value of c is 12
Line 2 - Value of c is 61
Line 3 - Value of c is 49
Line 5 - Value of c is 15
Assignment Operators
The following table lists all the assignment operators supported by Go language:
31
Go Programming
C <<= 2 is same as C = C
<<= Left shift AND assignment operator
<< 2
C >>= 2 is same as C = C
>>= Right shift AND assignment operator
>> 2
Example
Try the following example to understand all the assignment operators available in
Go programming language:
package main
import "fmt"
func main() {
var a int = 21
var c int
c = a
fmt.Printf("Line 1 - = Operator Example, Value of c = %d\n", c )
c += a
fmt.Printf("Line 2 - += Operator Example, Value of c = %d\n", c )
c -= a
fmt.Printf("Line 3 - -= Operator Example, Value of c = %d\n", c )
c *= a
fmt.Printf("Line 4 - *= Operator Example, Value of c = %d\n", c )
32
Go Programming
c /= a
fmt.Printf("Line 5 - /= Operator Example, Value of c = %d\n", c )
c = 200;
c <<= 2
fmt.Printf("Line 6 - <<= Operator Example, Value of c = %d\n", c )
c >>= 2
fmt.Printf("Line 7 - >>= Operator Example, Value of c = %d\n", c )
c &= 2
fmt.Printf("Line 8 - &= Operator Example, Value of c = %d\n", c )
c ^= 2
fmt.Printf("Line 9 - ^= Operator Example, Value of c = %d\n", c )
c |= 2
fmt.Printf("Line 10 - |= Operator Example, Value of c = %d\n", c )
When you compile and execute the above program, it produces the following
result:
33
Go Programming
Miscellaneous Operators
There are a few other important operators supported by Go Language
including sizeof and ?:.
Example
Try following example to understand all the miscellaneous operators available in
Go programming language:
package main
import "fmt"
func main() {
var a int = 4
var b int32
var c float32
var ptr *int
When you compile and execute the above program, it produces the following
result:
34
Go Programming
Operators Precedence in Go
Operator precedence determines the grouping of terms in an expression. This
affects how an expression is evaluated. Certain operators have higher precedence
than others; for example, the multiplication operator has higher precedence than
the addition operator.
Here, operators with the highest precedence appear at the top of the table, and
those with the lowest appear at the bottom. Within an expression, higher
precedence operators will be evaluated first.
35
Go Programming
Example
Try the following example to understand the operator precedence available in Go
programming language:
package main
import "fmt"
func main() {
var a int = 20
var b int = 10
var c int = 15
var d int = 5
var e int;
e = (a + b) * c / d; // ( 30 * 15 ) / 5
fmt.Printf("Value of (a + b) * c / d is : %d\n", e );
e = ((a + b) * c) / d; // (30 * 15 ) / 5
fmt.Printf("Value of ((a + b) * c) / d is : %d\n" , e );
e = a + (b * c) / d; // 20 + (150/5)
fmt.Printf("Value of a + (b * c) / d is : %d\n" , e );
}
36
Go Programming
When you compile and execute the above program, it produces the following
result:
Value of (a + b) * c / d is : 90
Value of ((a + b) * c) / d is : 90
Value of (a + b) * (c / d) is : 90
Value of a + (b * c) / d is : 50
37
9. DECISION MAKING Go Programming
Decision making structures require that the programmer specify one or more
conditions to be evaluated or tested by the program, along with a statement or
statements to be executed if the condition is determined to be true, and optionally,
other statements to be executed if the condition is determined to be false.
Following is the general form of a typical decision making structure found in most
of the programming languages:
Statement Description
38
Go Programming
The if Statement
An if statement consists of a boolean expression followed by one or more
statements.
Syntax
The syntax of an if statement in Go programming language is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
If the boolean expression evaluates to true, then the block of code inside the if
statement is executed. If boolean expression evaluates to false, then the first set
of code after the end of the if statement (after the closing curly brace) is executed.
Flow Diagram
39
Go Programming
Example
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 10
When the above code is compiled and executed, it produces the following result:
Syntax
The syntax of an if...else statement in Go programming language is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
40
Go Programming
If the boolean expression evaluates to true, then the if block of code is executed,
otherwise else block of code is executed.
Flow Diagram
Example
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100;
41
Go Programming
} else {
/* if condition is false then print the following */
fmt.Printf("a is not less than 20\n" );
}
fmt.Printf("value of a is : %d\n", a);
When the above code is compiled and executed, it produces the following result:
Nested if Statement
It is always legal in Go programming to nest if-else statements, which means you
can use one if or else if statement inside another if or else if statement(s).
Syntax
The syntax for a nested if statement is as follows:
if( boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
if(boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
}
}
You can nest else if...else in the similar way as you have nested if statement.
Example
package main
import "fmt"
func main() {
42
Go Programming
When the above code is compiled and executed, it produces the following result:
43
Go Programming
Expression Switch
The syntax for expression switch statement in Go programming is as follows:
You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
The constant-expression for a case must be the same data type as the
variable in the switch, and it must be a constant or a literal.
A switch statement can have an optional default case, which must appear
at the end of the switch. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case.
44
Go Programming
Flow Diagram
Example
package main
import "fmt"
func main() {
/* local variable definition */
var grade string = "B"
var marks int = 90
switch marks {
case 90: grade = "A"
case 80: grade = "B"
case 50,60,70 : grade = "C"
45
Go Programming
switch {
case grade == "A" :
fmt.Printf("Excellent!\n" )
case grade == "B", grade == "C" :
fmt.Printf("Well done\n" )
case grade == "D" :
fmt.Printf("You passed\n" )
case grade == "F":
fmt.Printf("Better try again\n" )
default:
fmt.Printf("Invalid grade\n" );
}
fmt.Printf("Your grade is %s\n", grade );
}
When the above code is compiled and executed, it produces the following result:
Well done
Excellent!
Your grade is A
Type Switch
The syntax for a type switch statement in Go programming is as follows:
switch x.(type){
case type:
statement(s);
case type:
statement(s);
/* you can have any number of case statements */
default: /* Optional */
statement(s);
}
46
Go Programming
You can have any number of case statements within a switch. Each case is
followed by the value to be compared to and a colon.
The type for a case must be the same data type as the variable in the
switch, and it must be a valid data type.
A switch statement can have an optional default case, which must appear
at the end of the switch. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case.
Example
package main
import "fmt"
func main() {
var x interface{}
switch i := x.(type) {
case nil:
fmt.Printf("type of x :%T",i)
case int:
fmt.Printf("x is int")
case float64:
fmt.Printf("x is float64")
case func(int) float64:
fmt.Printf("x is func(int)")
case bool, string:
fmt.Printf("x is bool or string")
default:
fmt.Printf("don't know the type")
}
47
Go Programming
When the above code is compiled and executed, it produces the following result:
type of x :<nil>
select {
case communication clause :
statement(s);
case communication clause :
statement(s);
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
You can have any number of case statements within a select. Each case is
followed by the value to be compared to and a colon.
When the channel operation occurs, the statements following that case is
executed. No break is needed in the case statement.
A select statement can have an optional default case, which must appear
at the end of the select. The default case can be used for performing a task
when none of the cases is true. No break is needed in the default case.
Example
package main
import "fmt"
func main() {
var c1, c2, c3 chan int
var i1, i2 int
select {
48
Go Programming
case i1 = <-c1:
fmt.Printf("received ", i1, " from c1\n")
case c2 <- i2:
fmt.Printf("sent ", i2, " to c2\n")
case i3, ok := (<-c3): // same as: i3, ok := <-c3
if ok {
fmt.Printf("received ", i3, " from c3\n")
} else {
fmt.Printf("c3 is closed\n")
}
default:
fmt.Printf("no communication\n")
}
}
When the above code is compiled and executed, it produces the following result:
no communication
While using ifelse ifelse statements, there are a few points to keep in mind:
An if can have zero or one else's and it must come after any else if's.
An if can have zero to many else if's and they must come before the else.
Once an else if succeeds, none of the remaining else if's or else's will be
tested.
Syntax
The syntax of if...else if...else statement in Go programming language is:
if(boolean_expression 1)
{
/* Executes when the boolean expression 1 is true */
}
else if( boolean_expression 2)
{
/* Executes when the boolean expression 2 is true */
49
Go Programming
}
else if( boolean_expression 3)
{
/* Executes when the boolean expression 3 is true */
}
else
{
/* executes when the none of the above condition is true */
}
Example
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100
50
Go Programming
When the above code is compiled and executed, it produces the following result:
51
10. LOOPS Go Programming
There may be a situation when you need to execute a block of code several
number of times. In general, statements are executed sequentially: the first
statement in a function is executed first, followed by the second, and so on.
nested loops These are one or multiple loops inside any for loop.
for Loop
A for loop is a repetition control structure. It allows you to write a loop that needs
to execute a specific number of times.
52
Go Programming
Syntax
The syntax of for loop in Go programming language is:
o The init step is executed first, and only once. This step allows you to
declare and initialize any loop control variables. You are not required to
put a statement here, as long as a semicolon appears.
o After the body of the for loop executes, the flow of control jumps back
up to the increment statement. This statement allows you to update
any loop control variables. This statement can be left blank, as long as
a semicolon appears after the condition.
o The condition is now evaluated again. If it is true, the loop executes and
the process repeats itself (body of loop, then increment step, and then
again the condition). After the condition becomes false, the for loop
terminates.
If range is available, then the for loop executes for each item in the range.
53
Go Programming
Flow Diagram
Example
package main
import "fmt"
func main() {
var b int = 15
var a int
numbers := [6]int{1, 2, 3, 5}
54
Go Programming
for a < b {
a++
fmt.Printf("value of a: %d\n", a)
}
When the above code is compiled and executed, it produces the following result:
value of a: 0
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
value of a: 8
value of a: 9
value of a: 1
value of a: 2
value of a: 3
value of a: 4
value of a: 5
value of a: 6
value of a: 7
55
Go Programming
value of a: 8
value of a: 9
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of x = 1 at 0
value of x = 2 at 1
value of x = 3 at 2
value of x = 5 at 3
value of x = 0 at 4
value of x = 0 at 5
Syntax
The syntax for a nested for loop statement in Go is as follows:
56
Go Programming
Example
The following program uses a nested for loop to find the prime numbers from 2 to
100:
package main
import "fmt"
func main() {
/* local variable definition */
var i, j int
When the above code is compiled and executed, it produces the following result:
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
57
Go Programming
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
53 is prime
59 is prime
61 is prime
67 is prime
71 is prime
73 is prime
79 is prime
83 is prime
89 is prime
97 is prime
The break statement in Go programming language has the following two usages:
58
Go Programming
If you are using nested loops, the break statement will stop the execution of the
innermost loop and start executing the next line of code after the block.
Syntax
The syntax for a break statement in Go is as follows:
break;
Flow Diagram
Example
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 10
59
Go Programming
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
In case of the for loop, continue statement causes the conditional test and
increment portions of the loop to execute.
Syntax
The syntax for a continue statement in Go is as follows:
continue;
60
Go Programming
Flow Diagram
Example
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 10
/* do loop execution */
for a < 20 {
if a == 15 {
/* skip the iteration */
a = a + 1;
continue;
61
Go Programming
}
fmt.Printf("value of a: %d\n", a);
a++;
}
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Syntax
The syntax for a goto statement in Go is as follows:
goto label;
..
.
label: statement;
Here, label can be any plain text except Go keyword and it can be set anywhere
in the Go program above or below to goto statement.
62
Go Programming
Flow Diagram
Example
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 10
/* do loop execution */
LOOP: for a < 20 {
if a == 15 {
/* skip the iteration */
a = a + 1
63
Go Programming
goto LOOP
}
fmt.Printf("value of a: %d\n", a)
a++
}
}
When the above code is compiled and executed, it produces the following result:
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 16
value of a: 17
value of a: 18
value of a: 19
package main
import "fmt"
func main() {
for true {
fmt.Printf("This loop will run forever.\n");
}
}
64
Go Programming
When the conditional expression is absent, it is assumed to be true. You may have
an initialization and increment expression, but C programmers more commonly
use the for(;;) construct to signify an infinite loop.
65
11. FUNCTIONS Go Programming
A function declaration tells the compiler about a function name, return type, and
parameters. A function definition provides the actual body of the function.
The Go standard library provides numerous built-in functions that your program
can call. For example, the function len() takes arguments of various types and
returns the length of the type. If a string is passed to it, the function returns the
length of the string in bytes. If an array is passed to it, the function returns the
length of the array.
Defining a Function
The general form of a function definition in Go programming language is as
follows:
Function Name: It is the actual name of the function. The function name
and the parameter list together constitute the function signature.
66
Go Programming
Example
The following source code shows a function called max(). This function takes two
parameters num1 and num2 and returns the maximum between the two:
Calling a Function
While creating a Go function, you give a definition of what the function has to do.
To use a function, you will have to call that function to perform the defined task.
When a program calls a function, the program control is transferred to the called
function. A called function performs a defined task and when its return statement
is executed or when its function-ending closing brace is reached, it returns the
program control back to the main program.
To call a function, you simply need to pass the required parameters along with its
function name. If the function returns a value, then you can store the returned
value. For example:
package main
import "fmt"
func main() {
67
Go Programming
We have kept the max() function along with the main() function and compiled the
source code. While running the final executable, it would produce the following
result:
package main
import "fmt"
68
Go Programming
func main() {
a, b := swap("Mahesh", "Kumar")
fmt.Println(a, b)
}
When the above code is compiled and executed, it produces the following result:
Kumar Mahesh
Function Arguments
If a function is to use arguments, it must declare variables that accept the values
of the arguments. These variables are called the formal parameters of the
function.
The formal parameters behave like other local variables inside the function and
are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a
function:
By default, Go uses call by value to pass arguments. In general, it means the code
within a function cannot alter the arguments used to call the function. The above
program, while calling the max() function, used the same method.
69
Go Programming
Call by Value
The call by value method of passing arguments to a function copies the actual
value of an argument into the formal parameter of the function. In this case,
changes made to the parameter inside the function have no effect on the
argument.
return temp;
}
Now, let us call the function swap() by passing actual values as in the following
example:
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100
var b int = 200
70
Go Programming
return temp;
}
Put the above code in a single C file, and then compile and execute it. It will
produce the following result:
It shows that there is no change in the values though they had been changed
inside the function.
Call by Reference
The call by reference method of passing arguments to a function copies the
address of an argument into the formal parameter. Inside the function, the
address is used to access the actual argument used in the call. This means that
changes made to the parameter affect the passed argument.
To pass the value by reference, argument pointers are passed to the functions
just like any other value. Accordingly, you need to declare the function parameters
as pointer types as in the following function swap(), which exchanges the values
of the two integer variables pointed to by its arguments.
71
Go Programming
*x = *y /* put y into x */
*y = temp /* put temp into y */
}
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100
var b int= 200
72
Go Programming
Put the above code in a single C file, and then compile and execute it. It produces
the following result:
It shows that the change has reflected outside the function as well, unlike call by
value where the changes do not reflect outside the function.
Function Usage
A function can be used in the following ways:
package main
import (
"fmt"
"math"
)
func main(){
/* declare a function variable */
getSquareRoot := func(x float64) float64 {
return math.Sqrt(x)
73
Go Programming
When the above code is compiled and executed, it produces the following result:
Function Closures
Go programming language supports anonymous functions which can act as
function closures. Anonymous functions are used when we want to define a
function inline without passing any name to it.
package main
import "fmt"
func main(){
/* nextNumber is now a function with i as 0 */
nextNumber := getSequence()
74
Go Programming
fmt.Println(nextNumber())
fmt.Println(nextNumber())
When the above code is compiled and executed, it produces the following result:
1
2
3
1
2
Method
Go programming language supports special types of functions called methods. In
method declaration syntax, a "receiver" is present to represent the container of
the function. This receiver can be used to call a function using "." operator. For
example:
Syntax
func (variable_name variable_data_type) function_name() [return_type]{
/* function body*/
}
package main
import (
"fmt"
"math"
)
/* define a circle */
type Circle strut {
75
Go Programming
x,y,radius float64
}
func main(){
circle := Circle(x:0, y:0, radius:5)
fmt.Printf("Circle area: %f", circle.area())
}
When the above code is compiled and executed, it produces the following result:
76
12. SCOPE RULES Go Programming
Let us find out what are local and global variables and what are formal
parameters.
Local Variables
Variables that are declared inside a function or a block are called local variables.
They can be used only by statements that are inside that function or block of code.
Local variables are not known to functions outside their own. The following
example uses local variables. Here all the variables a, b, and c are local to the
main() function.
package main
import "fmt"
func main() {
/* local variable declaration */
var a, b, c int
/* actual initialization */
a = 10
b = 20
c = a + b
fmt.Printf ("value of a = %d, b = %d and c = %d\n", a, b, c)
}
When the above code is compiled and executed, it produces the following result:
77
Go Programming
Global Variables
Global variables are defined outside of a function, usually on top of the program.
Global variables hold their value throughout the lifetime of the program and they
can be accessed inside any of the functions defined for the program.
A global variable can be accessed by any function. That is, a global variable is
available for use throughout the program after its declaration. The following
example uses both global and local variables:
package main
import "fmt"
func main() {
/* actual initialization */
a = 10
b = 20
g = a + b
When the above code is compiled and executed, it produces the following result:
A program can have the same name for local and global variables but the value of
the local variable inside a function takes preference. For example:
package main
import "fmt"
78
Go Programming
func main() {
/* local variable declaration */
var g int = 10
When the above code is compiled and executed, it produces the following result:
value of g = 10
Formal Parameters
Formal parameters are treated as local variables with-in that function and they
take preference over the global variables. For example:
package main
import "fmt"
func main() {
/* local variable declaration in main function */
var a int = 10
var b int = 20
var c int = 0
79
Go Programming
return a + b;
}
When the above code is compiled and executed, it produces the following result:
value of a in main() = 10
value of a in sum() = 10
value of b in sum() = 20
value of c in main() = 30
int 0
float32 0
pointer Nil
80
13. STRINGS Go Programming
Strings, which are widely used in Go programming, are a read-only slice of bytes.
In the Go programming language, strings are slices. The Go platform provides
various libraries to manipulate strings:
unicode
regexp
strings
Creating Strings
The most direct way to create a string is to write:
Whenever it encounters a string literal in your code, the compiler creates a string
object with its value. In this case, it is "Hello world!'.
A string literal holds valid UTF-8 sequences called runes. A string holds arbitrary
bytes.
package main
import "fmt"
func main() {
var greeting = "Hello world!"
81
Go Programming
Note: The string literal is immutable. Once it is created, a string literal cannot be
changed.
String Length
len(str) method returns the number of bytes contained in a string literal.
package main
import "fmt"
func main() {
var greeting = "Hello world!"
String Length is : 12
Concatenating Strings
The strings package includes a method join for concatenating multiple strings:
82
Go Programming
package main
import (
"fmt"
"strings"
)
func main() {
greetings := []string{"Hello","world!"}
fmt.Println(strings.Join(greetings, " "))
}
Hello world!
83
14. ARRAYS Go Programming
Go programming language provides a data structure called the array, which can
store a fixed-size sequential collection of elements of the same data type. An array
is used to store a collection of data, but it is often more useful to think of an array
as a collection of variables of the same type.
All arrays consist of contiguous memory locations. The lowest address corresponds
to the first element and the highest address to the last element.
Declaring Arrays
To declare an array in Go, a programmer specifies the type of the elements and
the number of elements required by an array as follows:
Initializing Arrays
You can initialize an array in Go, either one by one or using a single statement as
follows:
84
Go Programming
The number of values between the braces { } cannot be larger than the number
of elements that we declare for the array between the square brackets [ ].
If you omit the size of the array, an array just big enough to hold the initialization
is created. Therefore, if you write:
You will create exactly the same array as you did in the previous example.
Following is an example to assign a single element of the array:
balance[4] = 50.0
The above statement assigns element number 5th in the array with a value of
50.0. All arrays have 0 as the index of their first element which is also called base
index and last index of an array will be total size of the array minus 1. Following
is the pictorial representation of the same array we discussed above:
The above statement will take the 10th element from the array and assign the
value to salary variable. Following is an example which will use all the above-
mentioned three concepts, viz. declaration, assignment, and accessing arrays:
package main
import "fmt"
func main() {
var n [10]int /* n is an array of 10 integers */
var i,j int
85
Go Programming
When the above code is compiled and executed, it produces the following result:
Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109
Go Arrays in Detail
There are important concepts related to array which should be clear to a Go
programmer:
Concept Description
86
Go Programming
Multidimensional Arrays in Go
Go programming language allows multidimensional arrays. Here is the general
form of a multidimensional array declaration:
Two-Dimensional Arrays
A two-dimensional array is the simplest form of a multidimensional array. A two-
dimensional array is, in essence, a list of one-dimensional arrays. To declare a
two-dimensional integer array of size [x, y], you would write something as follows:
Where variable_type can be any valid Go data type and arrayName can be a
valid Go identifier. A two-dimensional array can be taken as a table having x
number of rows and y number of columns. A 2-dimensional array a, which contains
three rows and four columns can be shown as below:
a = [3][4]int{
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
87
Go Programming
The above statement takes the 4th element from the 3rd row of the array. You
can verify it in the above diagram. Let us check the following program where we
have used nested loop to handle a two-dimensional array:
package main
import "fmt"
func main() {
/* an array with 5 rows and 2 columns*/
var a = [5][2]int{ {0,0}, {1,2}, {2,4}, {3,6},{4,8}}
var i, j int
When the above code is compiled and executed, it produces the following result:
a[0][0]: 0
a[0][1]: 0
a[1][0]: 1
a[1][1]: 2
a[2][0]: 2
a[2][1]: 4
88
Go Programming
a[3][0]: 3
a[3][1]: 6
a[4][0]: 4
a[4][1]: 8
As explained above, you can have arrays with any number of dimensions, although
it is likely that most of the arrays you create will be of one or two dimensions.
Way-1
Formal parameters as a sized array as follows:
Way-2
Formal parameters as an unsized array as follows:
89
Go Programming
Example
Now, consider the following function, which will take an array as an argument
along with another argument and based on the passed arguments, it will return
the average of the numbers passed through the array as follows:
return avg;
}
package main
import "fmt"
func main() {
/* an int array with 5 elements */
var balance = []int {1000, 2, 3, 17, 50}
var avg float32
90
Go Programming
return avg;
}
When the above code is compiled together and executed, it produces the following
result:
As you can see, the length of the array doesn't matter as far as the function is
concerned because Go performs no bounds checking for formal parameters.
91
15. POINTERS Go Programming
Pointers in Go are easy and fun to learn. Some Go programming tasks are
performed more easily with pointers, and other tasks, such as call by reference,
cannot be performed without using pointers. So it becomes necessary to learn
pointers to become a perfect Go programmer.
As you know, every variable is a memory location and every memory location has
its address defined which can be accessed using ampersand (&) operator, which
denotes an address in memory. Consider the following example, which will print
the address of the variables defined:
package main
import "fmt"
func main() {
var a int = 10
When the above code is compiled and executed, it produces the following result:
So you understood what is memory address and how to access it. Now let us see
what pointers are.
Here, type is the pointer's base type; it must be a valid C data type and var-
name is the name of the pointer variable. The asterisk * you used to declare the
pointer is the same asterisk that you use for multiplication. However, in this
statement, the asterisk is being used to designate a variable as a pointer. The
following are valid pointer declarations:
92
Go Programming
The actual data type of the value of all pointers, whether integer, float, or
otherwise., is the same, a long hexadecimal number that represents a memory
address. The only difference between pointers of different data types is the data
type of the variable or constant that the pointer points to.
All these operations are carried out using the unary operator * that returns the
value of the variable located at the address specified by its operand. The following
example demonstrates how to perform these operations:
package main
import "fmt"
func main() {
var a int= 20 /* actual variable declaration */
var ip *int /* pointer variable declaration */
When the above code is compiled and executed, it produces the following result:
93
Go Programming
Nil Pointers in Go
Go compiler assign a nil value to a pointer variable in case you do not have exact
address to be assigned. This is done at the time of variable declaration. A pointer
that is assigned nil is called a nil pointer.
The nil pointer is a constant with a value of zero defined in several standard
libraries. Consider the following program:
package main
import "fmt"
func main() {
var ptr *int
When the above code is compiled and executed, it produces the following result:
On most of the operating systems, programs are not permitted to access memory
at address 0 because that memory is reserved by the operating system. However,
the memory address 0 has special significance; it signals that the pointer is not
intended to point to an accessible memory location. But by convention, if a pointer
contains the nil (zero) value, it is assumed to point to nothing.
Go Pointers in Detail
Pointers have many but easy concepts and they are very important to Go
programming. The following concepts of pointers should be clear to a Go
programmer:
94
Go Programming
Concept Description
Go Array of Pointers
Before we understand the concept of arrays of pointers, let us consider the
following example, which makes use of an array of 3 integers:
package main
import "fmt"
func main() {
a := []int{10,100,200}
var i int
When the above code is compiled and executed, it produces the following result:
Value of a[0] = 10
Value of a[1] = 100
Value of a2] = 200
95
Go Programming
There may be a situation when we want to maintain an array, which can store
pointers to an int or string or any other data type available. The following
statement declares an array of pointers to an integer:
This declares ptr as an array of MAX integer pointers. Thus, each element in ptr,
now holds a pointer to an int value. The following example makes use of three
integers, which will be stored in an array of pointers as follows:
package main
import "fmt"
const MAX int = 3
func main() {
a := []int{10,100,200}
var i int
var ptr [MAX]*int;
When the above code is compiled and executed, it produces the following result:
Value of a[0] = 10
Value of a[1] = 100
Value of a[2] = 200
Go Pointer to Pointer
A pointer to a pointer is a form of chain of pointers. Normally, a pointer contains
the address of a variable. When we define a pointer to a pointer, the first pointer
contains the address of the second pointer, which points to the location that
contains the actual value as shown below.
96
Go Programming
package main
import "fmt"
func main() {
var a int
var ptr *int
var pptr **int
a = 3000
97
Go Programming
When the above code is compiled and executed, it produces the following result:
In the following example, we pass two pointers to a function and change the value
inside the function which reflects back in the calling function:
package main
import "fmt"
func main() {
/* local variable definition */
var a int = 100
var b int= 200
98
Go Programming
When the above code is compiled and executed, it produces the following result:
99
16. STRUCTURES Go Programming
Go arrays allow you to define variables that can hold several data items of the
same kind. Structure is another user-defined data type available in Go
programming, which allows you to combine data items of different kinds.
Structures are used to represent a record. Suppose you want to keep track of the
books in a library. You might want to track the following attributes of each book:
Title
Author
Subject
Book ID
Defining a Structure
To define a structure, you must use type and struct statements. The struct
statement defines a new data type, with multiple members for your program. The
type statement binds a name with the type which is struct in our case. The format
of the struct statement is as follows:
Once a structure type is defined, it can be used to declare variables of that type
using the following syntax.
100
Go Programming
package main
import "fmt"
func main() {
var Book1 Books /* Declare Book1 of type Book */
var Book2 Books /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "Go Programming"
Book1.author = "Mahesh Kumar"
Book1.subject = "Go Programming Tutorial"
Book1.book_id = 6495407
/* book 2 specification */
Book2.title = "Telecom Billing"
Book2.author = "Zara Ali"
Book2.subject = "Telecom Billing Tutorial"
Book2.book_id = 6495700
101
Go Programming
When the above code is compiled and executed, it produces the following result:
package main
import "fmt"
func main() {
var Book1 Books /* Declare Book1 of type Book */
var Book2 Books /* Declare Book2 of type Book */
102
Go Programming
/* book 1 specification */
Book1.title = "Go Programming"
Book1.author = "Mahesh Kumar"
Book1.subject = "Go Programming Tutorial"
Book1.book_id = 6495407
/* book 2 specification */
Book2.title = "Telecom Billing"
Book2.author = "Zara Ali"
Book2.subject = "Telecom Billing Tutorial"
Book2.book_id = 6495700
When the above code is compiled and executed, it produces the following result:
103
Go Programming
Pointers to Structures
You can define pointers to structures in the same way as you define pointer to any
other variable as follows:
Now, you can store the address of a structure variable in the above defined pointer
variable. To find the address of a structure variable, place the & operator before
the structure name as follows:
struct_pointer = &Book1;
To access the members of a structure using a pointer to that structure, you must
use the "." operator as follows:
struct_pointer.title;
package main
import "fmt"
func main() {
var Book1 Books /* Declare Book1 of type Book */
var Book2 Books /* Declare Book2 of type Book */
/* book 1 specification */
Book1.title = "Go Programming"
Book1.author = "Mahesh Kumar"
104
Go Programming
/* book 2 specification */
Book2.title = "Telecom Billing"
Book2.author = "Zara Ali"
Book2.subject = "Telecom Billing Tutorial"
Book2.book_id = 6495700
When the above code is compiled and executed, it produces the following result:
105
17. SLICES Go Programming
Defining a slice
To define a slice, you can declare it as an array without specifying its size.
Alternatively, you can use make function to create a slice.
package main
import "fmt"
func main {
var numbers = make([]int,3,5)
printSlice(numbers)
}
When the above code is compiled and executed, it produces the following result:
106
Go Programming
Nil slice
If a slice is declared with no inputs, then by default, it is initialized as nil. Its length
and capacity are zero. For example:
package main
import "fmt"
func main {
var numbers []int
printSlice(numbers)
if(numbers == nil){
fmt.printf("slice is nil")
}
}
When the above code is compiled and executed, it produces the following result:
Subslicing
Slice allows lower-bound and upper bound to be specified to get its subslice using
[lower-bound:upper-bound]. For example:
107
Go Programming
package main
import "fmt"
func main {
/* create a slice */
numbers := []int{0,1,2,3,4,5,6,7,8}
printSlice(numbers)
numbers1 := make([]int,0,5)
printSlice(numbers1)
108
Go Programming
When the above code is compiled and executed, it produces the following result:
package main
import "fmt"
func main {
var numbers []int
printSlice(numbers)
109
Go Programming
When the above code is compiled and executed, it produces the following result:
110
18. RANGE Go Programming
The range keyword is used in for loop to iterate over items of an array, slice,
channel or map. With arrays and slices, it returns the index of the item as integer.
With maps, it returns the key of the next key-value pair. Range either returns one
value or two. If only one value is used on the left of a range expression, it is the
1st value in the following table.
Example
The following paragraph shows how to use range:
package main
import "fmt"
func main {
/* create a slice */
numbers := []int{0,1,2,3,4,5,6,7,8}
/* create a map*/
coutryCapitalMap := map[string] string
{"France":"Paris","Italy":"Rome","Japan":"Tokyo"}
111
Go Programming
When the above code is compiled and executed, it produces the following result:
Slice item 0 is 0
Slice item 1 is 1
Slice item 2 is 2
Slice item 3 is 3
Slice item 4 is 4
Slice item 5 is 5
Slice item 6 is 6
Slice item 7 is 7
Slice item 8 is 8
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
112
19. MAPS Go Programming
Go provides another important data type named map which maps unique keys to
values. A key is an object that you use to retrieve a value at a later date. Given a
key and a value, you can store the value in a Map object. After the value is stored,
you can retrieve it by using its key.
Defining a Map
You must use make function to create a map.
/* define the map as nil map can not be assigned any value*/
map_variable = make(map[key_data_type]value_data_type)
Example
The following example illustrates how to create and use a map:
package main
import "fmt"
func main {
var coutryCapitalMap map[string]string
/* create a map*/
coutryCapitalMap = make(map[string]string)
113
Go Programming
When the above code is compiled and executed, it produces the following result:
delete() Function
delete() function is used to delete an entry from a map. It requires the map and
the corresponding key which is to be deleted. For example:
package main
import "fmt"
func main {
/* create a map*/
coutryCapitalMap := map[string] string
{"France":"Paris","Italy":"Rome","Japan":"Tokyo","India":"New Delhi"}
fmt.Println("Original map")
114
Go Programming
/* print map */
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
/* delete an entry */
delete(countryCapitalMap,"France");
fmt.Println("Entry for France is deleted")
fmt.Println("Updated map")
/* print map */
for country := range countryCapitalMap {
fmt.Println("Capital of",country,"is",countryCapitalMap[country])
}
}
When the above code is compiled and executed, it produces the following result:
Original Map
Capital of France is Paris
Capital of Italy is Rome
Capital of Japan is Tokyo
Capital of India is New Delhi
Entry for France is deleted
Updated Map
Capital of India is New Delhi
Capital of Italy is Rome
Capital of Japan is Tokyo
115
20. RECURSION Go Programming
Recursion is the process of repeating items in a self-similar way. The same concept
applies in programming languages as well. If a program allows to call a function
inside the same function, then it is called a recursive function call. Take a look at
the following example:
func recursion() {
recursion() /* function calls itself */
}
func main() {
recursion()
}
Examples of Recursion in Go
Recursive functions are very useful to solve many mathematical problems such as
calculating factorial of a number, generating a Fibonacci series, etc.
package main
import "fmt"
116
Go Programming
func main {
var i int = 15
fmt.Printf("Factorial of %d is %d\n", i, factorial(i))
}
When the above code is compiled and executed, it produces the following result:
Factorial of 15 is 2004310016
package main
import "fmt"
func main() {
var i int
for i = 0; i < 10; i++ {
fmt.Printf("%d\t%n", fibonaci(i))
}
}
When the above code is compiled and executed, it produces the following result:
117
Go Programming
0 1 1 2 3 5 8 13 21 34
118
21. TYPE CASTING Go Programming
Type casting is a way to convert a variable from one data type to another data
type. For example, if you want to store a long value into a simple integer then you
can type cast long to int. You can convert values from one type to another using
the cast operator. Its syntax is as follows:
type_name(expression)
Example
Consider the following example where the cast operator causes the division of one
integer variable by another to be performed as a floating number operation.
package main
import "fmt"
func main() {
var sum int = 17
var count int = 5
var mean float32
maen = float32(sum)/float32(count)
fmt.Printf("Value of mean : %f\n",mean)
}
When the above code is compiled and executed, it produces the following result:
119
22. INTERFACES Go Programming
Syntax
/* define an interface */
type interface_name interface {
method_name1 [return_type]
method_name2 [return_type]
method_name3 [return_type]
...
method_namen [return_type]
}
/* define a struct */
type struct_name struct {
/* variables */
}
120
Go Programming
Example
package main
import (
"fmt"
"math"
)
/* define an interface */
type Shape interface {
area() float64
}
/* define a circle */
type Circle struct {
x,y,radius float64
}
/* define a rectangle */
type Rectangle struct {
width, height float64
}
121
Go Programming
func main() {
circle := Circle{x:0,y:0,radius:5}
rectangle := Rectangle {width:10, height:5}
When the above code is compiled and executed, it produces the following result:
122
23. ERROR HANDLING Go Programming
Functions normally return error as last return value. Use errors.New to construct
a basic error message as following:
if err != nil {
fmt.Println(err)
}
Example
package main
import "errors"
import "fmt"
import "math"
123
Go Programming
func main() {
result, err:= Sqrt(-1)
if err != nil {
fmt.Println(err)
}else {
fmt.Println(result)
}
if err != nil {
fmt.Println(err)
}else {
fmt.Println(result)
}
}
When the above code is compiled and executed, it produces the following result:
124