Go Programming Language
Go Programming Language
GO PROGRAMMING LANGUAGE
What is Go?
Go Python C++
1
GO Programming Language (UCETA – Ranganadh)
Does not support classes and Has classes and Has classes and objects
objects objects
Notes:
Go Get Started
Go Install IDE
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
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!")
}
go run .\helloworld.go
Hello World!
Go Syntax
Package declaration
Import packages
Functions
Statements and expressions
3
GO Programming Language (UCETA – Ranganadh)
Example
package main
import ("fmt")
func main() {
fmt.Println("Hello World!")
}
Example explained
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.
Go Statements
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).
4
GO Programming Language (UCETA – Ranganadh)
Example
package main
import ("fmt")
func main()
{
fmt.Println("Hello World!")
}
Go Comments
Comments can be used to explain the code, and to make it more readable.
Go Single-line Comments
Any text between // and the end of the line is ignored by the compiler (will
not be executed).
Go Multi-line Comments
Go Variable Types
5
GO Programming Language (UCETA – Ranganadh)
Syntax
var variablename type = value
Note: You always have to specify either type or value (or both).
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).
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)
}
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
There are some small differences between the var var :=:
var :=
Can be used inside and outside of Can only be used inside functions
functions
Example
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)
}
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)
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
10
GO Programming Language (UCETA – Ranganadh)
Example
package main
import ("fmt")
const PI = 3.14
func main() {
fmt.Println(PI)
}
Go Output Functions
Print()
Println()
Printf()
The Print() function prints its arguments with their default format.
Example
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
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
package main
import ("fmt")
12
GO Programming Language (UCETA – Ranganadh)
func main() {
var i,j = 10,20
fmt.Print(i,j)
}
Result:
10 20
Example
package main
import ("fmt")
func main() {
var i,j string = "Hello","World"
fmt.Println(i,j)
}
Result:
Hello World
The Printf() function first formats its argument based on the given formatting
verb and then prints them.
Example
package main
import ("fmt")
13
GO Programming Language (UCETA – Ranganadh)
func main() {
var i string = "Hello"
var j int = 15
Result:
Go Formatting Verbs
Formatting Verbs for Printf()
Go offers several formatting verbs that can be used with the Printf() function.
Verb Description
14
GO Programming Language (UCETA – Ranganadh)
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
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
%o Base 8
16
GO Programming Language (UCETA – Ranganadh)
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
The following verbs can be used with the string data type:
17
GO Programming Language (UCETA – Ranganadh)
Verb Description
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
The following verbs can be used with the float data type:
Verb Description
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
or
or
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
package main
import ("fmt")
func main() {
var cars = [4]string{"Volvo", "BMW", "Ford", "Mazda"}
fmt.Print(cars)
}
Result:
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]
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.
23
GO Programming Language (UCETA – Ranganadh)
Syntax
slice_name := []datatype{values}
myslice := []int{}
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
package main
import ("fmt")
func main() {
myslice1 := []int{}
fmt.Println(len(myslice1))
fmt.Println(cap(myslice1))
fmt.Println(myslice1)
Result:
0
0
24
GO Programming Language (UCETA – Ranganadh)
[]
4
4
[Go Slices Are Powerful]
Example
package main
import ("fmt")
func main() {
arr1 := [6]int{10, 11, 12, 13, 14,15}
myslice := arr1[2:4]
Result:
Go Operators
Arithmetic Operators
+ - * / % ++ --
Assignment Operators
25
GO Programming Language (UCETA – Ranganadh)
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)
}
Example
package main
import ("fmt")
func main() {
var x = 10
x +=5
fmt.Println(x)
}
Comparison Operators
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 Reverse the result, returns false if !(x < 5 && x <
not the result is true 10)
Go Conditions
27
GO Programming Language (UCETA – Ranganadh)
The if Statement
Example
package main
import ("fmt")
func main() {
if 20 > 18 {
fmt.Println("20 is greater than 18")
}
}
28
GO Programming Language (UCETA – Ranganadh)
Syntax
if condition {
// code to be executed if condition is true
} else {
// code to be executed if condition is false
}
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.")
}
}
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
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.
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
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:
Use the switch statement to select one of many code blocks to be executed.
31
GO Programming Language (UCETA – Ranganadh)
Syntax
switch expression {
case x:
// code block
case y:
// code block
case z:
...
default:
// code block
}
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
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
}
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
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
package main
import ("fmt")
func main() {
var i int
34
GO Programming Language (UCETA – Ranganadh)
Example
package main
import ("fmt")
func main() {
var i,j int
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
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
Go For Loops
The for loop loops through a block of code a specified number of times.
Go for Loop
Loops are handy if you want to run the same code over and over again, each
time with a different value.
Syntax
36
GO Programming Language (UCETA – Ranganadh)
Example 1
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
Example 2
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 is used to skip one or more iterations in the loop. It
then continues with the next iteration in the loop.
Example
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
Example
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
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 is used to more easily iterate through the elements of an
array, slice or map. It returns both the index and the value.
Syntax
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
Create a Function
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)
Example
package main
import ("fmt")
func myMessage() {
fmt.Println("I just got executed!")
}
func main() {
myMessage() // call the function
}
Result:
Example
package main
import ("fmt")
func main() {
familyName("Liam")
familyName("Jenny")
42
GO Programming Language (UCETA – Ranganadh)
familyName("Anja")
}
Result:
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
Example
Here, myFunction() receives two integers (x and y) and returns their addition
(x + y) as integer (int):
package main
import ("fmt")
func main() {
fmt.Println(myFunction(1, 2))
}
Result:
43
GO Programming Language (UCETA – Ranganadh)
Recursion Functions
Example
package main
import ("fmt")
func main(){
testcount(1)
}
Result:
1
2
3
4
5
6
7
8
9
10
Go Structures
44
GO Programming Language (UCETA – Ranganadh)
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.
Declare a Struct
Syntax
Example
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.
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")
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
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
The length of a map is the number of its elements. You can find it using
the len() function.
Syntax
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:
Syntax
map_name[key] = value
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)
48
GO Programming Language (UCETA – Ranganadh)
fmt.Println(a)
}
Result:
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:
49
GO Programming Language (UCETA – Ranganadh)
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:
50