[go: up one dir, main page]

0% found this document useful (0 votes)
31 views50 pages

Go Programming Language

Uploaded by

Royal chodagiri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
31 views50 pages

Go Programming Language

Uploaded by

Royal chodagiri
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 50

GO Programming Language (UCETA – Ranganadh)

GO PROGRAMMING LANGUAGE

What is Go?

 Go is a cross-platform, open source programming language


 Go can be used to create high-performance applications
 Go is a fast, statically typed, compiled language known for its
simplicity and efficiency
 Go was developed at Google by Robert Griesemer, Rob Pike, and Ken
Thompson in 2007
 Go's syntax is similar to C++

What is Go Used For?

 Web development (server-side)


 Developing network-based programs
 Developing cross-platform enterprise applications
 Cloud-native development

Go Compared to Python and C++

Go Python C++

Statically typed Dynamically typed Statically typed

Fast run time Slow run time Fast run time

Compiled Interpreted Compiled

Fast compile time Interpreted Slow compile time

Supports concurrency No built-in Supports concurrency

1
GO Programming Language (UCETA – Ranganadh)

through goroutines and concurrency through threads


channel mechanism

Has automatic garbage Has automatic Does not have automatic


collection garbage collection garbage collection

Does not support classes and Has classes and Has classes and objects
objects objects

Does not support inheritance Supports inheritance Supports inheritance

Notes:

 Compilation time refers to translating the code into an executable program


 Concurrency is performing multiple things out-of-order, or at the same
time, without affecting the final outcome
 Statically typed means that the variable types are known at compile time

Go Get Started

To start using Go, you need two things:

 A text editor, like VS Code, to write Go code


 A compiler, like GCC, to translate the Go code into a language that the
computer will understand

There are many text editors and compilers to choose from.

Go Install IDE

An IDE (Integrated Development Environment) is used to edit AND compile


the code.

Popular IDE's include Visual Studio Code (VS Code), Vim, Eclipse, and
Notepad. These are all free, and they can be used to both edit and debug Go
code.

2
GO Programming Language (UCETA – Ranganadh)

Go Quickstart

Let's create our first Go program.

 Launch the VS Code editor


 Open the extension manager or alternatively, press Ctrl + Shift + x
 In the search box, type "go" and hit enter
 Find the Go extension by the GO team at Google and install the
extension
 After the installation is complete, open the command palette by
pressing Ctrl + Shift + p
 Run the Go: Install/Update Tools command
 Select all the provided tools and click OK

VS Code is now configured to use Go.

Create a new file (File > New File). Copy and paste the following code and
save the file as helloworld.go (File > Save As):

helloworld.go
package main
import ("fmt")

func main() {
fmt.Println("Hello World!")
}

Now, run the code: Open a terminal in VS Code and type:

go run .\helloworld.go

Hello World!

Go Syntax

A Go file consists of the following parts:

 Package declaration
 Import packages
 Functions
 Statements and expressions

Look at the following code, to understand it better:

3
GO Programming Language (UCETA – Ranganadh)

Example
package main
import ("fmt")

func main() {
fmt.Println("Hello World!")
}

Example explained

Line 1: In Go, every program is part of a package. We define this using


the package keyword. In this example, the program belongs to
the main package.

Line 2: import ("fmt") lets us import files included in the fmt package.

Line 3: A blank line. Go ignores white space. Having white spaces in code
makes it more readable.

Line 4: func main() {} is a function. Any code inside its curly brackets {} will
be executed.

Line 5: fmt.Println() is a function made available from the fmt package. It is


used to output/print text. In our example it will output "Hello World!".

Go Statements

fmt.Println("Hello World!") is a statement.

In Go, statements are separated by ending a line (hitting the Enter key) or by
a semicolon ";".

Hitting the Enter key adds ";" to the end of the line implicitly (does not show
up in the source code).

The left curly bracket { cannot come at the start of a line.

Run the following code and see what happens:

4
GO Programming Language (UCETA – Ranganadh)

Example
package main
import ("fmt")

func main()
{
fmt.Println("Hello World!")
}

Go Comments

A comment is a text that is ignored upon execution.

Comments can be used to explain the code, and to make it more readable.

Comments can also be used to prevent code execution when testing an


alternative code.

Go supports single-line or multi-line comments.

Go Single-line Comments

Single-line comments start with two forward slashes (//).

Any text between // and the end of the line is ignored by the compiler (will
not be executed).

Go Multi-line Comments

Multi-line comments start with /* and ends with */.

Any text between /* and */ will be ignored by the compiler:

Go Variable Types

In Go, there are different types of variables, for example:

 int- stores integers (whole numbers), such as 123 or -123

5
GO Programming Language (UCETA – Ranganadh)

 float32- stores floating point numbers, with decimals, such as 19.99 or


-19.99
 string - stores text, such as "Hello World". String values are surrounded
by double quotes
 bool- stores values with two states: true or false

Declaring (Creating) Variables

In Go, there are two ways to declare a variable:

1. With the var keyword:

Use the var keyword, followed by variable name and type:

Syntax
var variablename type = value

Note: You always have to specify either type or value (or both).

2. With the := sign:

Use the := sign, followed by the variable value:

Syntax
variablename := value

Note: In this case, the type of the variable is inferred from the value
(means that the compiler decides the type of the variable, based on the
value).

Note: It is not possible to declare a variable using :=, without assigning a


value to it.

Variable Declaration With Initial Value

If the value of a variable is known from the start, you can declare the
variable and assign a value to it on one line:

6
GO Programming Language (UCETA – Ranganadh)

Example
package main
import ("fmt")

func main() {
var student1 string = "John" //type is string
var student2 = "Jane" //type is inferred
x := 2 //type is inferred

fmt.Println(student1)
fmt.Println(student2)
fmt.Println(x)
}

Variable Declaration Without Initial Value

In Go, all variables are initialized. So, if you declare a variable without an
initial value, its value will be set to the default value of its type:

Example
package main
import ("fmt")

func main() {
var a string
var b int
var c bool

fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}

By running the code, we can see that they already have the default values of
their respective types:

 a is ""

7
GO Programming Language (UCETA – Ranganadh)

 b is 0
 c is false

Difference Between var and :=

There are some small differences between the var var :=:

var :=

Can be used inside and outside of Can only be used inside functions
functions

Variable declaration and value Variable declaration and value


assignment can be done assignment cannot be done
separately separately (must be done in the same
line)

Example

This example shows declaring variables outside of a function, with


the var keyword:

package main
import ("fmt")

var a int
var b int = 2
var c = 3

func main() {
a=1
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}

Go Multiple Variable Declaration


8
GO Programming Language (UCETA – Ranganadh)

In Go, it is possible to declare multiple variables in the same line.

Example

This example shows how to declare multiple variables in the same line:

package main
import ("fmt")

func main() {
var a, b, c, d int = 1, 3, 5, 7

fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}

Note: If you use the type keyword, it is only possible to declare one type of
variable per line.

If the type keyword is not specified, you can declare different types of
variables in the same line:

Example
package main
import ("fmt")

func main() {
var a, b = 6, "Hello"
c, d := 7, "World!"

fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}

9
GO Programming Language (UCETA – Ranganadh)

Go Variable Declaration in a Block

Multiple variable declarations can also be grouped together into a block for
greater readability:

Example
package main
import ("fmt")

func main() {
var (
a int
b int = 1
c string = "hello"
)

fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
}

Go Constants

If a variable should have a fixed value that cannot be changed, you can use
the const keyword.

The const keyword declares the variable as "constant", which means that it
is unchangeable and read-only.

Syntax
const CONSTNAME type = value

Note: The value of a constant must be assigned when you declare it.

Declaring a Constant

Here is an example of declaring a constant in Go:

10
GO Programming Language (UCETA – Ranganadh)

Example
package main
import ("fmt")

const PI = 3.14

func main() {
fmt.Println(PI)
}

Go Output Functions

Go has three functions to output text:

 Print()
 Println()
 Printf()

The Print() Function

The Print() function prints its arguments with their default format.

Example

Print the values of i and j:

package main
import ("fmt")

func main() {
var i,j string = "Hello","World"

fmt.Print(i)
fmt.Print(j)
}

Result:

HelloWorld

11
GO Programming Language (UCETA – Ranganadh)

Example

If we want to print the arguments in new lines, we need to use \n.

package main
import ("fmt")

func main() {
var i,j string = "Hello","World"

fmt.Print(i, "\n")
fmt.Print(j, "\n")
}

Result:

Hello
World

Example

It is also possible to only use one Print() for printing multiple variables.

package main
import ("fmt")

func main() {
var i,j string = "Hello","World"

fmt.Print(i, "\n",j)
}

Result:

Hello
World

Example

Print() inserts a space between the arguments if neither are strings:

package main
import ("fmt")

12
GO Programming Language (UCETA – Ranganadh)

func main() {
var i,j = 10,20

fmt.Print(i,j)
}

Result:

10 20

The Println() Function

The Println() function is similar to Print() with the difference that a


whitespace is added between the arguments, and a newline is added at the
end:

Example
package main
import ("fmt")

func main() {
var i,j string = "Hello","World"

fmt.Println(i,j)
}

Result:

Hello World

The Printf() Function

The Printf() function first formats its argument based on the given formatting
verb and then prints them.

Here we will use two formatting verbs:

 %v is used to print the value of the arguments


 %T is used to print the type of the arguments

Example
package main
import ("fmt")

13
GO Programming Language (UCETA – Ranganadh)

func main() {
var i string = "Hello"
var j int = 15

fmt.Printf("i has value: %v and type: %T\n", i, i)


fmt.Printf("j has value: %v and type: %T", j, j)
}

Result:

i has value: Hello and type: string


j has value: 15 and type: int

Go Formatting Verbs
Formatting Verbs for Printf()

Go offers several formatting verbs that can be used with the Printf() function.

General Formatting Verbs

The following verbs can be used with all data types:

Verb Description

%v Prints the value in the default format

%#v Prints the value in Go-syntax format

%T Prints the type of the value

14
GO Programming Language (UCETA – Ranganadh)

%% Prints the % sign

Example
package main
import ("fmt")

func main() {
var i = 15.5
var txt = "Hello World!"

fmt.Printf("%v\n", i)
fmt.Printf("%#v\n", i)
fmt.Printf("%v%%\n", i)
fmt.Printf("%T\n", i)

fmt.Printf("%v\n", txt)
fmt.Printf("%#v\n", txt)
fmt.Printf("%T\n", txt)
}

Result:

15.5
15.5
15.5%
float64
Hello World!
"Hello World!"
string

Integer Formatting Verbs

The following verbs can be used with the integer data type:

Verb Description

15
GO Programming Language (UCETA – Ranganadh)

%b Base 2

%d Base 10

%+d Base 10 and always show sign

%o Base 8

%O Base 8, with leading 0o

%x Base 16, lowercase

%X Base 16, uppercase

%#x Base 16, with leading 0x

%4d Pad with spaces (width 4, right justified)

%-4d Pad with spaces (width 4, left justified)

16
GO Programming Language (UCETA – Ranganadh)

%04d Pad with zeroes (width 4

Example
package main
import ("fmt")

func main() {
var i = 15

fmt.Printf("%b\n", i)
fmt.Printf("%d\n", i)
fmt.Printf("%+d\n", i)
fmt.Printf("%o\n", i)
fmt.Printf("%O\n", i)
fmt.Printf("%x\n", i)
fmt.Printf("%X\n", i)
fmt.Printf("%#x\n", i)
fmt.Printf("%4d\n", i)
fmt.Printf("%-4d\n", i)
fmt.Printf("%04d\n", i)
}

Result:

1111
15
+15
17
0o17
f
F
0xf
15
15
0015

String Formatting Verbs

The following verbs can be used with the string data type:
17
GO Programming Language (UCETA – Ranganadh)

Verb Description

%s Prints the value as plain string

%q Prints the value as a double-quoted string

%8s Prints the value as plain string (width 8, right justified)

%-8s Prints the value as plain string (width 8, left justified)

%x Prints the value as hex dump of byte values

%x Prints the value as hex dump with spaces

Example
package main
import ("fmt")

func main() {
var txt = "Hello"

fmt.Printf("%s\n", txt)
fmt.Printf("%q\n", txt)
fmt.Printf("%8s\n", txt)
fmt.Printf("%-8s\n", txt)
fmt.Printf("%x\n", txt)
fmt.Printf("% x\n", txt)
}

18
GO Programming Language (UCETA – Ranganadh)

Result:

Hello
"Hello"
Hello
Hello
48656c6c6f
48 65 6c 6c 6f

Float Formatting Verbs

The following verbs can be used with the float data type:

Verb Description

%e Scientific notation with 'e' as exponent

%f Decimal point, no exponent

%.2f Default width, precision 2

%6.2f Width 6, precision 2

%g Exponent as needed, only necessary digits

Example
package main
import ("fmt")

func main() {
var i = 3.141
19
GO Programming Language (UCETA – Ranganadh)

fmt.Printf("%e\n", i)
fmt.Printf("%f\n", i)
fmt.Printf("%.2f\n", i)
fmt.Printf("%6.2f\n", i)
fmt.Printf("%g\n", i)
}

Result:

3.141000e+00
3.141000
3.14
3.14
3.141

Go Arrays

Arrays are used to store multiple values of the same type in a single
variable, instead of declaring separate variables for each value.

Declare an Array

In Go, there are two ways to declare an array:

1. With the var keyword:


Syntax
var array_name = [length]datatype{values} // here length is defined

or

var array_name = [...]datatype{values} // here length is inferred

2. With the := sign:


Syntax
array_name := [length]datatype{values} // here length is defined

or

array_name := [...]datatype{values} // here length is inferred

20
GO Programming Language (UCETA – Ranganadh)

Array Examples
Example

This example declares two arrays (arr1 and arr2) with defined lengths:

package main
import ("fmt")

func main() {
var arr1 = [3]int{1,2,3}
arr2 := [5]int{4,5,6,7,8}

fmt.Println(arr1)
fmt.Println(arr2)
}

Result:

[1 2 3]
[4 5 6 7 8]

Example

This example declares an array of strings:

package main
import ("fmt")

func main() {
var cars = [4]string{"Volvo", "BMW", "Ford", "Mazda"}
fmt.Print(cars)
}

Result:

[Volvo BMW Ford Mazda]

Access Elements of an Array

You can access a specific array element by referring to the index number.

In Go, array indexes start at 0. That means that [0] is the first element, [1] is
the second element, etc.

21
GO Programming Language (UCETA – Ranganadh)

Example

This example shows how to access the first and third elements in the prices
array:

package main
import ("fmt")

func main() {
prices := [3]int{10,20,30}

fmt.Println(prices[0])
fmt.Println(prices[2])
}

Result:

10
30

Array Initialization

If an array or one of its elements has not been initialized in the code, it is
assigned the default value of its type.

Tip: The default value for int is 0, and the default value for string is "".

Example
package main
import ("fmt")

func main() {
arr1 := [5]int{} //not initialized
arr2 := [5]int{1,2} //partially initialized
arr3 := [5]int{1,2,3,4,5} //fully initialized

fmt.Println(arr1)
fmt.Println(arr2)
fmt.Println(arr3)
}

Result:

22
GO Programming Language (UCETA – Ranganadh)

[0 0 0 0 0]
[1 2 0 0 0]
[1 2 3 4 5]

Find the Length of an Array

The len() function is used to find the length of an array:

Example
package main
import ("fmt")

func main() {
arr1 := [4]string{"Volvo", "BMW", "Ford", "Mazda"}
arr2 := [...]int{1,2,3,4,5,6}

fmt.Println(len(arr1))
fmt.Println(len(arr2))
}

Result:

4
6

Go Slices

Slices are similar to arrays, but are more powerful and flexible.

Like arrays, slices are also used to store multiple values of the same type in
a single variable.

However, unlike arrays, the length of a slice can grow and shrink as you see
fit.

In Go, there are several ways to create a slice:

 Using the []datatype{values} format


 Create a slice from an array
 Using the make() function

Create a Slice With []datatype{values}

23
GO Programming Language (UCETA – Ranganadh)

Syntax
slice_name := []datatype{values}

A common way of declaring a slice is like this:

myslice := []int{}

The code above declares an empty slice of 0 length and 0 capacity.

To initialize the slice during declaration, use this:

myslice := []int{1,2,3}

The code above declares a slice of integers of length 3 and also the capacity
of 3.

In Go, there are two functions that can be used to return the length and
capacity of a slice:

Example

This example shows how to create slices using the []datatype{values}


format:

package main
import ("fmt")

func main() {
myslice1 := []int{}
fmt.Println(len(myslice1))
fmt.Println(cap(myslice1))
fmt.Println(myslice1)

myslice2 := []string{"Go", "Slices", "Are", "Powerful"}


fmt.Println(len(myslice2))
fmt.Println(cap(myslice2))
fmt.Println(myslice2)
}

Result:

0
0

24
GO Programming Language (UCETA – Ranganadh)

[]
4
4
[Go Slices Are Powerful]

Example

This example shows how to create a slice from an array:

package main
import ("fmt")

func main() {
arr1 := [6]int{10, 11, 12, 13, 14,15}
myslice := arr1[2:4]

fmt.Printf("myslice = %v\n", myslice)


fmt.Printf("length = %d\n", len(myslice))
fmt.Printf("capacity = %d\n", cap(myslice))
}

Result:

myslice = [12 13]


length = 2
capacity = 4

Go Operators

Operators are used to perform operations on variables and values.

Arithmetic Operators

Arithmetic operators are used to perform common mathematical operations.

+ - * / % ++ --

Assignment Operators

25
GO Programming Language (UCETA – Ranganadh)

Assignment operators are used to assign values to variables.

In the example below, we use the assignment operator (=) to assign the
value 10 to a variable called x:

Example
package main
import ("fmt")

func main() {
var x = 10
fmt.Println(x)
}

The addition assignment operator (+=) adds a value to a variable:

Example
package main
import ("fmt")

func main() {
var x = 10
x +=5
fmt.Println(x)
}

Comparison Operators

Comparison operators are used to compare two values.

Note: The return value of a comparison is either true (1) or false (0).

In the following example, we use the greater than operator (>) to find out if
5 is greater than 3:

Example
package main
import ("fmt")

26
GO Programming Language (UCETA – Ranganadh)

func main() {
var x = 5
var y = 3
fmt.Println(x>y) // returns 1 (true) because 5 is greater than 3
}

Logical Operators

Logical operators are used to determine the logic between variables or


values:

Operato Name Description Example


r

&& Logical Returns true if both statements x < 5 && x <


and are true 10

|| Logical Returns true if one of the x < 5 || x < 4


or statements is true

! Logical Reverse the result, returns false if !(x < 5 && x <
not the result is true 10)

Go Conditions

A condition can be either true or false.

Go supports the usual comparison operators from mathematics:

 Less than <


 Less than or equal <=

27
GO Programming Language (UCETA – Ranganadh)

 Greater than >


 Greater than or equal >=
 Equal to ==
 Not equal to !=

Additionally, Go supports the usual logical operators:

 Logical AND &&


 Logical OR ||
 Logical NOT !

Go has the following conditional statements:

 Use if to specify a block of code to be executed, if a specified condition


is true
 Use else to specify a block of code to be executed, if the same
condition is false
 Use else if to specify a new condition to test, if the first condition is
false
 Use switch to specify many alternative blocks of code to be executed

The if Statement

Use the if statement to specify a block of Go code to be executed if a


condition is true.

Example
package main
import ("fmt")

func main() {
if 20 > 18 {
fmt.Println("20 is greater than 18")
}
}

28
GO Programming Language (UCETA – Ranganadh)

The else Statement

Use the else statement to specify a block of code to be executed if the


condition is false.

Syntax
if condition {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}

Using The if else Statement


Example

In this example, time (20) is greater than 18, so the if condition is false.
Because of this, we move on to the else condition and print to the screen
"Good evening". If the time was less than 18, the program would print "Good
day":

package main
import ("fmt")

func main() {
time := 20
if (time < 18) {
fmt.Println("Good day.")
} else {
fmt.Println("Good evening.")
}
}

The else if Statement

Use the else if statement to specify a new condition if the first condition
is false.

29
GO Programming Language (UCETA – Ranganadh)

Syntax
if condition1 {
// code to be executed if condition1 is true
} else if condition2 {
// code to be executed if condition1 is false and condition2 is true
} else {
// code to be executed if condition1 and condition2 are both false
}

Example

This example shows how to use an else if statement.

package main
import ("fmt")

func main() {
time := 22
if time < 10 {
fmt.Println("Good morning.")
} else if time < 20 {
fmt.Println("Good day.")
} else {
fmt.Println("Good evening.")
}
}

Result:

Good evening.

The Nested if Statement

You can have if statements inside if statements, this is called a nested if.

Syntax
if condition1 {
// code to be executed if condition1 is true
if condition2 {
// code to be executed if both condition1 and condition2 are true

30
GO Programming Language (UCETA – Ranganadh)

}
}

Example

This example shows how to use nested if statements:

package main
import ("fmt")

func main() {
num := 20
if num >= 10 {
fmt.Println("Num is more than 10.")
if num > 15 {
fmt.Println("Num is also more than 15.")
}
} else {
fmt.Println("Num is less than 10.")
}
}

Result:

Num is more than 10.


Num is also more than 15.

The switch Statement

Use the switch statement to select one of many code blocks to be executed.

The switch statement in Go is similar to the ones in C, C++, Java, JavaScript,


and PHP. The difference is that it only runs the matched case so it does not
need a break statement.

Single-Case switch Syntax

31
GO Programming Language (UCETA – Ranganadh)

Syntax
switch expression {
case x:
// code block
case y:
// code block
case z:
...
default:
// code block
}

This is how it works:

 The expression is evaluated once


 The value of the switch expression is compared with the values of
each case
 If there is a match, the associated block of code is executed
 The default keyword is optional. It specifies some code to run if there is
no case match

Example
package main
import ("fmt")

func main() {
day := 4

switch day {
case 1:
fmt.Println("Monday")
case 2:
fmt.Println("Tuesday")
case 3:
fmt.Println("Wednesday")
case 4:
fmt.Println("Thursday")
case 5:
fmt.Println("Friday")
32
GO Programming Language (UCETA – Ranganadh)

case 6:
fmt.Println("Saturday")
case 7:
fmt.Println("Sunday")
}
}

Result:

Thursday

The Multi-case switch Statement

It is possible to have multiple values for each case in the switch statement:

Syntax
switch expression {
case x,y:
// code block if expression is evaluated to x or y
case v,w:
// code block if expression is evaluated to v or w
case z:
...
default:
// code block if expression is not found in any cases
}

Multi-case switch Example

The example below uses the weekday number to return different text:

Example
package main
import ("fmt")

func main() {
day := 5

switch day {

33
GO Programming Language (UCETA – Ranganadh)

case 1,3,5:
fmt.Println("Odd weekday")
case 2,4:
fmt.Println("Even weekday")
case 6,7:
fmt.Println("Weekend")
default:
fmt.Println("Invalid day of day number")
}
}

Result:

Odd weekday

Go User Input

Go has multiple ways to receive inputs from the user.

The Scan() Function

The Scan() function receives the user input in raw format as space-separated
values and stores them in the variables. Newlines count as spaces.

Example

This example receives the value of i and prints it:

package main
import ("fmt")

func main() {
var i int

fmt.Print("Type a number: ")


fmt.Scan(&i)
fmt.Println("Your number is:", i)
}

You can have more than one user input.

34
GO Programming Language (UCETA – Ranganadh)

Example

This example receives the values of i and j and prints them:

package main
import ("fmt")

func main() {
var i,j int

fmt.Print("Type two numbers: ")


fmt.Scan(&i, &j)
fmt.Println("Your numbers are:", i, "and", j)
}

The Scanln() Function

The Scanln() function is similar to Scan(), but it stops scanning for inputs at a
newline (at the press of the Enter key.).

Example

This example receives the values of i and j and then prints them:

package main
import ("fmt")

func main() {
var i,j int

fmt.Print("Type two numbers: ")


fmt.Scanln(&i, &j)
fmt.Println("Your numbers are:", i, "and", j)
}

The Scanf() Function

The Scanf() function receives the inputs and stores them based on the
determined formats for its arguments.

35
GO Programming Language (UCETA – Ranganadh)

Example

This example receives the values of i and j and then prints them:

package main
import ("fmt")

func main() {
var i,j int

fmt.Print("Type two numbers: ")


fmt.Scanf("%v %v",&i, &j)
fmt.Println("Your numbers are:", i, "and", j)
}

Go For Loops

The for loop loops through a block of code a specified number of times.

The for loop is the only loop available in Go.

Go for Loop

Loops are handy if you want to run the same code over and over again, each
time with a different value.

Each execution of a loop is called an iteration.

The for loop can take up to three statements:

Syntax

for statement1; statement2; statement3 {


// code to be executed for each iteration
}

statement1 Initializes the loop counter value.

statement2 Evaluated for each loop iteration. If it evaluates to TRUE, the


loop continues. If it evaluates to FALSE, the loop ends.

statement3 Increases the loop counter value.

36
GO Programming Language (UCETA – Ranganadh)

Note: These statements don't need to be present as loops arguments.


However, they need to be present in the code in some form.

for Loop Examples

Example 1

This example will print the numbers from 0 to 4:

package main
import ("fmt")

func main() {
for i:=0; i < 5; i++ {
fmt.Println(i)
}
}

Result:

0
1
2
3
4

Example 1 explained

 i:=0; - Initialize the loop counter (i), and set the start value to 0

 i < 5; - Continue the loop as long as i is less than 5

 i++ - Increase the loop counter value by 1 for each iteration

Example 2

This example counts to 100 by tens:

package main
import ("fmt")

func main() {
for i:=0; i <= 100; i+=10 {

37
GO Programming Language (UCETA – Ranganadh)

fmt.Println(i)
}
}

Result:

0
10
20
30
40
50
60
70
80
90
100

The continue Statement

The continue statement is used to skip one or more iterations in the loop. It
then continues with the next iteration in the loop.

Example

This example skips the value of 3:

package main
import ("fmt")

func main() {
for i:=0; i < 5; i++ {
if i == 3 {
continue
}
fmt.Println(i)
}
}

Result:

38
GO Programming Language (UCETA – Ranganadh)

0
1
2
4

The break Statement

The break statement is used to break/terminate the loop execution.

Example

This example breaks out of the loop when i is equal to 3:

package main
import ("fmt")

func main() {
for i:=0; i < 5; i++ {
if i == 3 {
break
}
fmt.Println(i)
}
}

Result:

0
1
2

Nested Loops

It is possible to place a loop inside another loop.

Here, the "inner loop" will be executed one time for each iteration of the
"outer loop":

Example

package main
import ("fmt")

39
GO Programming Language (UCETA – Ranganadh)

func main() {
adj := [2]string{"big", "tasty"}
fruits := [3]string{"apple", "orange", "banana"}
for i:=0; i < len(adj); i++ {
for j:=0; j < len(fruits); j++ {
fmt.Println(adj[i],fruits[j])
}
}
}

Result:

big apple
big orange
big banana
tasty apple
tasty orange
tasty banana

The Range Keyword

The range keyword is used to more easily iterate through the elements of an
array, slice or map. It returns both the index and the value.

The range keyword is used like this:

Syntax

for index, value := range array|slice|map {


// code to be executed for each iteration
}

Example

This example uses range to iterate over an array and print both the indexes
and the values at each (idx stores the index, val stores the value):

package main
import ("fmt")

func main() {
fruits := [3]string{"apple", "orange", "banana"}
for idx, val := range fruits {
fmt.Printf("%v\t%v\n", idx, val)

40
GO Programming Language (UCETA – Ranganadh)

}
}

Result:

0 apple
1 orange
2 banana

Go Functions

A function is a block of statements that can be used repeatedly in a program.

A function will not execute automatically when a page loads.

A function will be executed by a call to the function.

Create a Function

To create (often referred to as declare) a function, do the following:

 Use the func keyword.

 Specify a name for the function, followed by parentheses ().

 Finally, add code that defines what the function should do, inside curly
braces {}.

Syntax

func FunctionName() {
// code to be executed
}

Call a Function

Functions are not executed immediately. They are "saved for later use", and
will be executed when they are called.

41
GO Programming Language (UCETA – Ranganadh)

In the example below, we create a function named "myMessage()". The


opening curly brace ( { ) indicates the beginning of the function code, and
the closing curly brace ( } ) indicates the end of the function. The function
outputs "I just got executed!". To call the function, just write its name
followed by two parentheses ():

Example

package main
import ("fmt")

func myMessage() {
fmt.Println("I just got executed!")
}

func main() {
myMessage() // call the function
}

Result:

I just got executed!

Function With Parameter Example

The following example has a function with one parameter (fname) of


type string. When the familyName() function is called, we also pass along a
name (e.g. Liam), and the name is used inside the function, which outputs
several different first names, but an equal last name:

Example

package main
import ("fmt")

func familyName(fname string) {


fmt.Println("Hello", fname, "Refsnes")
}

func main() {
familyName("Liam")
familyName("Jenny")

42
GO Programming Language (UCETA – Ranganadh)

familyName("Anja")
}

Result:

Hello Liam Refsnes


Hello Jenny Refsnes
Hello Anja Refsnes

Return Values

If you want the function to return a value, you need to define the data type
of the return value (such as int, string, etc), and also use the return keyword
inside the function:

Syntax

func FunctionName(param1 type, param2 type) type {


// code to be executed
return output
}

Function Return Example

Example

Here, myFunction() receives two integers (x and y) and returns their addition
(x + y) as integer (int):

package main
import ("fmt")

func myFunction(x int, y int) int {


return x + y
}

func main() {
fmt.Println(myFunction(1, 2))
}

Result:

43
GO Programming Language (UCETA – Ranganadh)

Recursion Functions

Go accepts recursion functions. A function is recursive if it calls itself and


reaches a stop condition.

In the following example, testcount() is a function that calls itself. We use


the x variable as the data, which increments with 1 (x + 1) every time we
recurse. The recursion ends when the x variable equals to 11 (x == 11).

Example

package main
import ("fmt")

func testcount(x int) int {


if x == 11 {
return 0
}
fmt.Println(x)
return testcount(x + 1)
}

func main(){
testcount(1)
}

Result:

1
2
3
4
5
6
7
8
9
10

Go Structures

44
GO Programming Language (UCETA – Ranganadh)

A struct (short for structure) is used to create a collection of members of


different data types, into a single variable.

While arrays are used to store multiple values of the same data type into a
single variable, structs are used to store multiple values of different data
types into a single variable.

A struct can be useful for grouping data together to create records.

Declare a Struct

To declare a structure in Go, use the type and struct keywords:

Syntax

type struct_name struct {


member1 datatype;
member2 datatype;
member3 datatype;
...
}

Example

Here we declare a struct type Person with the following


members: name, age, job and salary:

type Person struct {


name string
age int
job string
salary int
}

Tip: Notice that the struct members above have different data
types. name and job is of type string, while age and salary is of type int.

Access Struct Members

To access any member of a structure, use the dot operator (.) between the
structure variable name and the structure member:

45
GO Programming Language (UCETA – Ranganadh)

Example

package main
import ("fmt")

type Person struct {


name string
age int
job string
salary int
}

func main() {
var pers1 Person
var pers2 Person

// Pers1 specification
pers1.name = "Hege"
pers1.age = 45
pers1.job = "Teacher"
pers1.salary = 6000

// Pers2 specification
pers2.name = "Cecilie"
pers2.age = 24
pers2.job = "Marketing"
pers2.salary = 4500

// Access and print Pers1 info


fmt.Println("Name: ", pers1.name)
fmt.Println("Age: ", pers1.age)
fmt.Println("Job: ", pers1.job)
fmt.Println("Salary: ", pers1.salary)

// Access and print Pers2 info


fmt.Println("Name: ", pers2.name)
fmt.Println("Age: ", pers2.age)
fmt.Println("Job: ", pers2.job)
fmt.Println("Salary: ", pers2.salary)
}

46
GO Programming Language (UCETA – Ranganadh)

Result:

Name: Hege
Age: 45
Job: Teacher
Salary: 6000
Name: Cecilie
Age: 24
Job: Marketing
Salary: 4500

Go Maps

Maps are used to store data values in key:value pairs.

Each element in a map is a key:value pair.

A map is an unordered and changeable collection that does not allow


duplicates.

The length of a map is the number of its elements. You can find it using
the len() function.

The default value of a map is nil.

Maps hold references to an underlying hash table.

Go has multiple ways for creating maps.

Create Maps Using var and :=

Syntax

var a = map[KeyType]ValueType{key1:value1, key2:value2,...}


b := map[KeyType]ValueType{key1:value1, key2:value2,...}

Example

This example shows how to create maps in Go. Notice the order in the code
and in the output

47
GO Programming Language (UCETA – Ranganadh)

package main
import ("fmt")

func main() {
var a =
map[string]string{"brand": "Ford", "model": "Mustang", "year": "1964"}
b := map[string]int{"Oslo": 1, "Bergen": 2, "Trondheim": 3, "Stavanger": 4}

fmt.Printf("a\t%v\n", a)
fmt.Printf("b\t%v\n", b)
}

Result:

a map[brand:Ford model:Mustang year:1964]


b map[Bergen:2 Oslo:1 Stavanger:4 Trondheim:3]

Update and Add Map Elements

Updating or adding an elements are done by:

Syntax

map_name[key] = value

Example

This example shows how to update and add elements to a map.

package main
import ("fmt")

func main() {
var a = make(map[string]string)
a["brand"] = "Ford"
a["model"] = "Mustang"
a["year"] = "1964"

fmt.Println(a)

a["year"] = "1970" // Updating an element

48
GO Programming Language (UCETA – Ranganadh)

a["color"] = "red" // Adding an element

fmt.Println(a)
}

Result:

map[brand:Ford model:Mustang year:1964]


map[brand:Ford color:red model:Mustang year:1970]

Remove Element from Map

Removing elements is done using the delete() function.

Syntax

delete(map_name, key)

Example

package main
import ("fmt")

func main() {
var a = make(map[string]string)
a["brand"] = "Ford"
a["model"] = "Mustang"
a["year"] = "1964"

fmt.Println(a)

delete(a,"year")

fmt.Println(a)
}

Result:

map[brand:Ford model:Mustang year:1964]


map[brand:Ford model:Mustang]

49
GO Programming Language (UCETA – Ranganadh)

Iterate Over Maps

You can use range to iterate over maps.

Example

This example shows how to iterate over the elements in a map. Note the
order of the elements in the output.

package main
import ("fmt")

func main() {
a := map[string]int{"one": 1, "two": 2, "three": 3, "four": 4}

for k, v := range a {
fmt.Printf("%v : %v, ", k, v)
}
}

Result:

two : 2, three : 3, four : 4, one : 1,

50

You might also like