0% found this document useful (0 votes)
101 views

Introduction To Go Language Final PDF

Uploaded by

priyanka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
101 views

Introduction To Go Language Final PDF

Uploaded by

priyanka
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 220

“Develop a passion for learning.

Introduction to Go Language
Programming
THE BEST OF ALL WORLDS

Go Programming language
combines the freedom and syntax
of C languages and the usability
and abstraction of Python.
Freedom and syntax: pointers,
compilations, blocks, and more.
Usability and abstraction: garbage
collection, large assortment of
standard libraries, string
manipulation, and more.
Easy to use, such as Python, but
sophisticated enough for complex
development, similar to C / C++.

2
© 2018 by Innovation In Software Corporation
GO LANGUAGE
Go Language (golang) is an open source
language developed by Robert Griesemer,
Rob Pike, and Ken Thompson. It was
launched at the Google Open Source Blog
on November 10, 2009. Go was initially
developed for requirements set by
Google. Go was created partly from
frustration in using C++.
Go Language is made available under the
BSD 3-Clause "New" or "Revised" License.

“When the three of us got started, it was pure


research. The three of us got together and decided
that we hated C++. We started off with the idea that
all three of us had to be talked into every feature in
the language, so there was no extraneous garbage put
into the language for any reason.” – Ken Thompson

3
© 2018 by Innovation In Software Corporation
GO LANGUAGE PROJECTS
• Go-Ethereum
• Terraform
• Kubernetes
• Docker
• Etcd
• Revel
• InfluxDB

4
© 2018 by Innovation In Software Corporation
LOGISTICS
Class Hours: Telecommunication:
• Turn off or set
• Start time is 9am electronic devices to
vibrate
• End time is 4:30pm
• Reading or attending
• Class times may to devices can be
vary slightly for distracting to other
students
specific classes
• Try to delay until
• Breaks mid-morning breaks or after class
and afternoon (10
minutes)

Lunch: Miscellaneous
• Lunch is 11:45am • Courseware
to 1pm
• Yes, 1 hour and 15 • Bathroom
minutes • Fire drills
• Extra time for
email, phone calls,
or simply a walk.

5
© 2018 by Innovation In Software Corporation
DONIS MARSHALL
GO Language Practitioner
Microsoft MVP
Microsoft Certified
C++ Certified
Author

donis@innovationinsoftware.com

6
© 2018 by Innovation In Software Corporation
INTRODUCTION TO GO LANGUAGE
Go is C-like, small, and a strongly typed language. The language supports
low-level capabilities such as pointers and concurrency; while supporting
higher level features such as garbage collection and collections. Go
Language can be used as a procedural, functional, object-oriented
language, or some combination.
Code from the Go Language is compiled into binary unlike Python
language, which is an interpreted language. This allows for faster execution,
performance optimization, cross-platform deployment, and more. Go
Language scales efficiently making it easier to develop large applications.
One example is the better handling of package dependencies.
Robust library of open source packages that can be used with the Go
Language. Many of the standard packages are deployed here:
https://golang.org/pkg/
Go offers many features including Unicode strings, various data structures,
garbage collection, concurrency, file handling, and networking.

7
© 2018 by Innovation In Software Corporation
NO INHERITANCE
Go Language closes the door on
classes and inheritance. Instead,
composition is used for object
oriented programming. Traditionally,
there has been an overreliance on
inheritance in modern languages,
such as C++, Java, and Python.
In the Go Language, object oriented
programming is implemented with
structures and methods.
This is an article on the benefits of
composition over inheritance.
http://bit.ly/2H3mHxT

8
© 2018 by Innovation In Software Corporation
GO LANGUAGE ENVIRONMENT

9
© 2018 by Innovation In Software Corporation
PLATFORM AGNOSTIC
Go Language is platform agnostic. You can download Go Language for
Mac, Linux, or the Windows environment.
Here is the page for downloading Go Language for your environment. It
also documents operating system compatibility.
https://golang.org/doc/install

Operating system Architectures

FreeBSD 9.3 or later amd64, 386

Linux 2.6.23 or later with glibc amd64, 386, arm, arm64,s390x, ppc64le

macOS 10.8 or later amd64

Windows XP SP2 or later amd64, 386

10
© 2018 by Innovation In Software Corporation
GIT
GitHub is a web-based hosting service for version control of files.
Often a repository for open source code projects. You can store many
types of documents with GitHub; not just source code.
Git is an free and open source tool for distributed version control –
typically using GitHub as the repository sources. It is lightweight and
fast. Teams have preferred GIT and distributed version control in lieu
of centralized version control and tools such as Subversion, Perforce,
and ClearCase.
The Go Programming repository is stored in Github at:
https://github.com/golang/go
Git should be installed prior to using the Go Programming language.

11
© 2018 by Innovation In Software Corporation
CODING
Go Language supports UTF-8 text format, which is supported by many
editors. For this reason, formal IDEs are not required to edit, compile, and
run a Go program. You only need the Go Language, a text editor, and a
terminal / command prompt. However, an IDE can make creating a Go
program more convenient. Features such as syntax checking and
intellisense, which are common to formal IDEs, are helpful. Popular IDEs that
support Go Language include:
• VSCode
• IntelliJ
• Emacs
• Eclipse

12
© 2018 by Innovation In Software Corporation
VSCODE
In class, you can use any editor for Go
Language – whether an IDE or a
simple text editor. However, you are
expected to understand your tool.
In this class, the instructor will use
VSCode. It is free, complete IDE,
available in most environments, and
has a Go Language extension.

Download VSCode here:


https://code.visualstudio.com/download

13
© 2018 by Innovation In Software Corporation
THE GO PLAYGROUND

The Go Playground is an online


web-based environment for Go
Language development. A great
place to practice your
programming expertise for Go
Language. Now you can develop
in Go anywhere and 24/7.
You can also use the playground
for class.
The playground is found at:
https://play.golang.org/

14
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Lab 1- Setup

15
STEP 1
Here are the steps for creating an environment to develop Go
projects. These are generic steps and specific details may vary based
on your operating system and architecture.
You can skip some steps if completed previously. For example, no
need to install Git if already installed unless you want a more recent
version.
Speaking of Git, Step 1 is installing Git. Install Git from this web page.
https://git-scm.com/book/en/v2/Getting-Started-Installing-Git
At this page, you will also find documentation on installing GIT for
each environment.

16
© 2018 by Innovation In Software Corporation
STEP 2
Next step is installing the Go Language.
Here is the webpage to install the Go Language for a variety of target
environments.
https://golang.org/doc/install
You will also find installation documentation for each environment at this
page.
After the installation is completed, inspect the PATH, GOROOT, and
GOPATH environment variables. The PATH should include an entry
identifying the GO binary directory. GOROOT references the installation
directory, GOPATH is where the source code for your projects and packages
are located.
Test the Go command (go version) from the command prompt / terminal as
a smoke test of a successful installation.

17
© 2018 by Innovation In Software Corporation
STEP 3
Delve is a debugger for debugging Go applications. In addition, Delve
interestingly was developed using the Go Language.
Instructions for installing Delve are located here:
http://nanxiao.me/en/a-brief-intro-of-delve/
This webpage also provides basic documentation on debugging Go
Language source code using Delve.

18
© 2018 by Innovation In Software Corporation
STEP 4
Installing VSCode is the final step. Here is the installation page for
deploying VSCode to various environments.
https://code.visualstudio.com/docs/setup/setup-overview
After installation, start the VSCode application.
• From the left panel, install the Go extension.
• If extensions are not visible, select Extensions from the|
View menu. You can also select the Extension icon ( )
from the vertical toolbar.
• After installing, make sure to activate the Go extension.
You are ready to begin developing code using the Go
Language!

19
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

The Basics
Go Programming
GETTING STARTED
Hard to get started without a start. That would be considered a Yogi
Berra-ism.
http://nyp.st/2nWXCw7
This chapter provides a start on the Go Language. You will learn how
to create procedural, object oriented, and functional programs using
Go Language and with the help of annotated source code.
With this foundation, we can then backfill some of the concepts
introduced here in later modules.

21
© 2018 by Innovation In Software Corporation
PROCEDURAL
The founders of Go Programming understand the lasting
benefits of procedural programming. Object oriented
programming is not always the most ideal or
straightforward solution.
Every introduction, and some advanced, programming
classes have an “Hello, world!” program or some
variation.

22
© 2018 by Innovation In Software Corporation
HELLO.GO package main

import (

More versatile version of the standard


"fmt"

"os"
“hello, world” application. "strconv"

var hello = []string{"Hello", "Hola",

"Bon Jour", "Ciao", "こんにちは"}

func main() {

var index = 1

if len(os.Args) > 1 {

index, _ = strconv.Atoi(os.Args[1])

if(index < 1 || index > len(hello)) {

index=1

fmt.Println(hello[index-1])

23
}
© 2018 by Innovation In Software Corporation
HELLO.GO - EXPLAINED
package main 1

build an executable versus a shared package with


main as the entry point method (1) import (

"fmt"

import these shared packages (2) "os" 2


"strconv"

)
declare hello variable as a slice of strings(3) var hello = []string{"Hello", "Hola",
3
"Bon Jour", "Ciao", "こんにちは"}

declare index as an integer type(4) func main() {

var index = 1 4
if len(os.Args) > 1 {
convert command-line argument from string to
integer(5) index, _ = strconv.Atoi(os.Args[1]) 5
}

If index not within range, adjust to 1 (6)


if(index < 1 || index > len(hello)) { 6
index=1

print the correct hello based on command-line }


argument (7) fmt.Println(hello[index-1]) 7
}

24
© 2018 by Innovation In Software Corporation
SWAP.GO
package main

import "fmt"

Swap two values by-value and then func main() {

by-pointer.
a := 5
b := 10
a, b = swap1(a, b)
fmt.Println(a, b)

swap2(&a, &b)
fmt.Println(a, b)
}

func swap1(x int, y int) (int, int) {


return y, x
}

func swap2(x *int, y *int) {


*x, *y = *y, *x
return
}

25
© 2018 by Innovation In Software Corporation
SWAP.GO - EXPLAINED
package main 1
build an executable versus a shared package with
main as the entry point method (1) import "fmt" 2

func main() {

import fmt package (2) a := 5


3
b := 10
a, b = swap1(a, b)
4
short variable declaration for a and b with int type fmt.Println(a, b)
implied (3)
swap2(&a, &b) 5
fmt.Println(a, b)

call swap1 function and pass arguments by value (4) }

func swap1(x int, y int) (int, int) {


return y, x 6
call swap2 function and pass arguments by pointer }
(5)
func swap2(x *int, y *int) {
*x, *y = *y, *x
7
define swap1 function: two integer arguments, return
return swapped two integer arguments (6) }

define swap2 function: two integer pointer


arguments. Swap values at pointers. (7)

26
© 2018 by Innovation In Software Corporation
VARIADIC.GO
package main

import "fmt"

Go Language supports variable length func main() {

argument lists for functions. t1 := total(1, 5, 9, 3)


fmt.Println(t1)
}

func total(values ...int) int {


var result int
for _, item := range values {
result += item
}
return result
}

27
© 2018 by Innovation In Software Corporation
VARAIDIC .GO - EXPLAINED
package main 1

build an executable versus a shared package with import "fmt" 2


main as the entry point method (1)
func main() {
import fmt package (2)
t1 := total(1, 5, 9, 3) 3
fmt.Println(t1)
call total function with variable number of }
arguments (3)
func total(values ...int) int { 4
function signature for variadic function (4) var result int
for _, item := range values {
result += item 5
total the arguments (5)
}
return result
}

28
© 2018 by Innovation In Software Corporation
EMPLOYEE.GO

Creating custom / composite types package main


(struct) is easy in Go Language.
import "fmt"

type employee struct {


firstName string
lastName string
age int
weight int
}

func main() {
fred := employee{firstName: "Fred",
lastName: "Wilson", age: 45, weight: 156}
fmt.Println(fred)
}

29
© 2018 by Innovation In Software Corporation
EMPLOYEE.GO - EXPLAINED
build an executable (1)
package main 1

import fmt package (2) import "fmt" 2

type employee struct {

define the employee struct composite firstName string


3
type (3) lastName string
age int
weight int

declare variable fred as a struct


}

(employee) and initialize fields (4) func main() {


4
fred := employee{firstName: "Fred",
lastName: "Wilson", age: 45, weight: 156}

print fred variable (5) fmt.Println(fred)


5
}

30
© 2018 by Innovation In Software Corporation
RECTANGLE.GO package main

import "fmt"

func main() {

Like a class, you can assign functions r1 := rectangle{10, 20, 40, 30}
r1.Print()
to a struct, which is then called a r1.Draw()
method. This is object-oriented }

programming in Go Language. type rectangle struct {


top int
left int
bottom int
right int
}

func (r rectangle) Draw() {


fmt.Printf("Top: %d Left: %d Bottom: %d Right: %d",
r.top, r.left, r.bottom, r.right)
}

func (r rectangle) Print() {


fmt.Println(r)
}

31
© 2018 by Innovation In Software Corporation
RECTANGLE.GO - EXPLAINED package main 1

import "fmt" 2
build an executable (1)
func main() {
import fmt package (2) r1 := rectangle{10, 20, 40, 30} 3
r1.Print()
declare a rectangle and initialize the fields (3)
4
r1.Draw()
}
Print is a rectangle method and called using the dot
syntax (4b) type rectangle struct {
top int
left int 5
Draw is a rectangle method and called using the
dot syntax (4a) bottom int
right int

define the rectangle type (5) }

func (i isomething) Draw() { 6


define a Draw method for rectangle struct (6) fmt.Printf("Top: %d Left: %d Bottom: %d Right: %d",
r.top, r.left, r.bottom, r.right)
define a Print method for rectangle struct (7) }

func (r rectangle) Print() { 7


fmt.Println(r)

32
}
© 2018 by Innovation In Software Corporation
STRINGFUNC.GO
package main

import "fmt"

func main() {
Functions are first class variables in Go fmt.Println(stringModify("Test", addExclamation))

Language. As such, functions can be fmt.Println(stringModify("Test", right1))

used as parameters, and return


}

variables.
type modifier func(string) string

func stringModify(s string, f1 modifier) string {


return f1(s)
}

func addExclamation(s string) string {


return s + "!"
}

func right1(s string) string {


var temp string
for _, char := range s {
temp = temp + string(char+1)
}
return temp
}

33
© 2018 by Innovation In Software Corporation
STRINGFUNC.GO - EXPLAINED package main 1

import "fmt" 2
build an executable(1)
func main() {
import fmt package (2) fmt.Println(stringModify("Test", addExclamation))
fmt.Println(stringModify("Test", right1)) 3
call function to modify string (3) }

type modifier func(string) string 4


define a function type for a function accepting a
string parameter and returning a string (4) func stringModify(s string, f1 modifier) string {
return f1(s) 5

define stringModify function that calls a function to }


modify a string (5)
func addExclamation(s string) string {
6
define addExclamation function that modifies a return s + "!"
string: add “!” (6) }

func right1(s string) string { 7


define right1 function that modifies a string: shift var temp string temp=“”
bytes right one code point (7)
for _, char := range s { 46, 55, 66, 77 }
8
temp = temp + string(char+1)
access individual bytes of a string and increase
each code point by one (8) }
return temp

34
© 2018 by Innovation In Software Corporation }
GETURL.GO package main

import (

"fmt"

"io/ioutil"

"net/http"
Go Language is multi-purpose and "os"

ideal for general and system )

programming. This program makes an func main() {

HTTP request and displays the for _, url := range os.Args[1:] {

response. resp, err := http.Get(url)

if err != nil {

os.Exit(1)

b, err := ioutil.ReadAll(resp.Body)

resp.Body.Close()

if err != nil {

os.Exit(1)

fmt.Printf("%s\n\n", url)

fmt.Printf("%s\n\n", b)

35
}
© 2018 by Innovation In Software Corporation
GETURL.GO - EXPLAINED package main 1

import (

"fmt"
build an executable (1)
"io/ioutil" 2
"net/http"
import required packages (2)
"os"

)
Get function makes a HTTP request returns
response and error object (3) func main() {

for _, url := range os.Args[1:] {

resp, err := http.Get(url)


if error object not nil, an error has occurred and 3
program exits (4) if err != nil {
4
os.Exit(1)

}
ReadAll function reads the body text from the resp
object (5) b, err := ioutil.ReadAll(resp.Body) 5
resp.Body.Close()
6
if err != nil {
closes connection with server (6) os.Exit(1) 7
if error object not nil, an error has occurred and }
program exits (7)
fmt.Printf("%s\n\n", url)
8
fmt.Printf("%s\n\n", b)

Prints response data (8) }

36
© 2018 by Innovation In Software Corporation }
“Develop a passion for learning.”

Lab 2- Fibonacci

37
FIBONACCI
The Fibonacci series is a set of numbers where each element of the
series is the total of the previous two items. The first two numbers are
of the series are 0 and 1. The origin of the name is Filius Bonacci (i.e.,
Fibonacci) was an Italian mathematician during the middles ages and
died in 1250.
Here is a partial sequence:
0, 1, 1, 2, 3, 5, 8, 13, 21, and so on

38
© 2018 by Innovation In Software Corporation
GENERATE FIBONACCI
• Create a function that prints a segment of the Fibonacci series.
• The function has two parameters: starting and ending point
• The function returns the Fibonacci series
• An integer slice and the append method should help
• Maximum ending point is 100,000
• In main:
▪ Read beginning and ending values from command-line
▪ Call Fibonacci function
▪ Display results

39
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

The Basics
Go Programming
TYPES
Go Language supports a robust assortment of types. You can also
create custom and composite types, which are discussed in a later
module. This module reviews standard numeric and Boolean types.
Types are used to reserved memory for an application, which is
assigned an identifier. Identifiers are memory labels and provide a
convenient means to reference memory in a program.
This module also reviews various operations, including Boolean,
arithmetic, and bitwise that apply to standard types.

41
© 2018 by Innovation In Software Corporation
STANDARD TYPES
Type Description Type Description

bool true or false string Unicode string with UTF-8


encoding
byte Int8 uint Depends on implementation
float32 32-bit floating point variable. uint8 0 to 255
Mantissa reliable to 7-bits.
float64 64-bit floating point variable. uint16 0 to 65,535
Mantissa reliable to 15-bits.
uint32 0 to 4,294,967,295
int Depends on implementation
uint64 0 to 18,446,744,073,709,551,615
int8 -128 to 127

int16 -32,768 to 32,767

int32 -2,147,483,648 to -
2,147,483,647
int64 -9,223,372,036,854,775,808 to -
9,223,372,036,854,775,807
rune int32

42
© 2018 by Innovation In Software Corporation
ARITHMETIC OPERATORS

Type Description

+ Addition: L1 + R1

These are the arithmetic - Subtraction: L1 + R1

operators in Go Language. This + Positive: +L1


assumes L1 and R1 are - Negation: -L1
compatible types. * Multiplication: L1 * R1

/ Division: L1 / R1

% Remainder: L1 % R1

++ Postfix increment: L1++

-- Postfix decrement: L1--

43
© 2018 by Innovation In Software Corporation
POP QUIZ: WHAT IS THE ANSWER?

package main

import "fmt"

func main() {

fmt.Println((10*10) + (10/10))

10 MINUTES

44
© 2018 by Innovation In Software Corporation
MAXIMUM SIZE
The maximum or minimum size of many
standard types are available in the math
package.

package main

import (
"fmt"
"math"
)

func main() {
fmt.Println("MaxFloat32\t", math.MaxFloat32)
fmt.Println("MaxFloat64\t", math.MaxFloat64)
fmt.Println("MaxInt16\t", math.MaxInt16)
fmt.Println("MaxInt32\t", math.MaxInt32)
fmt.Println("MaxInt8\t", math.MaxInt8)
fmt.Println("MinInt16\t", math.MinInt16)
fmt.Println("MinInt32\t", math.MinInt32)
fmt.Println("MaxInt64\t", math.MaxInt64)
}

45
© 2018 by Innovation In Software Corporation
VARIABLES
Declaring a variable sets aside memory for a specific type and
value. You can declare variable using various syntax. A variable
declaration consists of an identifier, type, and value. The type
and value are optional. The type can be inferred, which is
different than dynamic. The value can default to some variation
of zero.
The identifier is essentially a label for the memory location where
the data is stored.

46
© 2018 by Innovation In Software Corporation
VARIABLES - 2
Variables are memory labels. package main
You can used pointers to access
the underlying address. More import "fmt"

about pointers later. func main() {


var xyz int = 5
var pxyz *int

pxyz = &xyz
fmt.Println(pxyz, *pxyz)
}

47
© 2018 by Innovation In Software Corporation
DECLARATIONS
Here are various methods to declare a package main

variable.
func main() {

var a int = 15 1

declare a typed variable of a specific type (1) 2


var b int

declare a variable with a default value (2) var c = 15 3

declare a variable with type inference (3) var f, g int = 5, 6 4

var (
declare multiple variables of the same type (4) h = 10
5
i = "test"

declare multiple variables of different types (5) j int


)
}

48
© 2018 by Innovation In Software Corporation
SHORT VARIABLE DECLARATIONS

You can declare variables using type


inference with short variable package main
declarations (:=), which is an
abbreviated syntax. This is the func main() {

preferred syntax of professional Go a := 1


Language programmers.
b, c := 5, 6
Short variable declarations must be
done within a function and not at file
d, e, f := 1, true, 4.56

scope. }

49
© 2018 by Innovation In Software Corporation
IDENTIFIERS
Identifiers are used to identify entities in the Go Language, such as
types, variables, functions, and so on.
• Identifiers are case sensitive
• Can consist of letters, digits, and some special characters are
allowed.
• First character must be a letter
• _ is the blank identifier for unused variables
• Methods that start with uppercase are considered public /
exported

50
© 2018 by Innovation In Software Corporation
DEFAULT VALUES
Uninitialized variables are
package main

assigned a default value, import "fmt"

which is a variation of zero.


func main() {
• Numeric types : 0 var i int
var f float64
• Boolean types : false var b bool

• Strings : “” var s string


fmt.Printf("%v %v %v %q\n",
i, f, b, s)
}

51
© 2018 by Innovation In Software Corporation
CONSTANTS
Constants are read only
package main

variables at run time. You func main() {

can define constants with


const a int = 5

literals or expressions const b int = 10 * a

involving other constant // Does not work

entities. const c int = 10 * d

You define a constant with var d int = 10

the const keyword as a }

prefix to the declaration;


instead of var.

52
© 2018 by Innovation In Software Corporation
UNTYPED CONST

Untyped const relies on type


inference. But there is another
important difference. Typed
const can only be used with
other entities of the same type.
Untyped const can be used in
an expression with entities of
similar type.

53
© 2018 by Innovation In Software Corporation
ENUMERATION
The Go Language does not support Enum const Bold = 1

types. Enum types are typically used for const Underline = 2 1

flags. However, there are three ways to


const Italics = 3

create something similar. const (


Small = 0
Medium = 1
2
Declare a constant for each flag (1)
Large = 2
XLarge = 3
)

abbreviation of syntax 1 (2) const (


South = iota
East
use the iota keyword to increment flags North 3
starting at zero for the first flag (3) West
)

54
© 2018 by Innovation In Software Corporation
BITWISE
package main
You can create a bitwise
enumeration using the bitwise
import "fmt"

operators. First, use the bitwise func main() {

left shift (1 <<) of iota on the type BitFlag int


const (
starting flag. The remaining Bold BitFlag = 1 << iota

flags can then default to their Underline

proper bitwise representation.


Italics
)
Second, combine the flags with result := Underline | Italics
the bitwise or ( | ).
fmt.Println("Flags", Bold, Underline, Italics)
fmt.Println("Result", result)
}

55
© 2018 by Innovation In Software Corporation
BOOLEAN
There are two Boolean values: true and false. Unlike C++, there is
strict type checking of Boolean types. Most notable, zero and non-
zero integral values cannot be cast to Boolean types.
There are a variety of Boolean operators as listed next. As an
efficiency, the Boolean operators will short circuit when possible.
Prevent the side affects of short circuiting by full evaluating Boolean
expressions before the Boolean operation.
The Boolean operators can be used with similar types: Booleans,
numbers, structs, and custom type. However, you cannot use the
Boolean operators to compare slices.

56
© 2018 by Innovation In Software Corporation
POP QUIZ: WHICH EXPRESSIONS WILL SHORT CIRCUIT?

func AFunc() bool {


return true
}

func BFunc() bool {


return false
}

var bool1 = AFunc() || BFunc() 1

var bool2 = AFunc() || true 2

var bool3 = false && BFunc() 3


var bool4 = AFunc() 4

var bool5 = BFunc() || AFunc() || false 5

10 MINUTES

57
© 2018 by Innovation In Software Corporation
BOOLEAN OPERATORS
Operator Description

== Equality: L == R

!= Non-equality: L != R

! Not: !L

|| Or: L || R

&& And: L && R

< Less than: L < R

> Greater than: L > R

<= Less than or equal: L <= R

>= Greater than or equal: L >= R

58
© 2018 by Innovation In Software Corporation
INTEGER
Go Language offers 11 different integral types – both signed and
unsigned. The byte type is a synonym for uint8, while rune is a
synonym for int32. Depending on your implementation, int may be
32 bit or 64 bit. Except for reading and writing persistent data, Go
Language developers typically use int.
Expressions require the same integer types. You can cast to create
compatible types. Casting from smaller to larger types is safe. The
results of casting from larger to smaller types is undefined.
You can also use integers with the bitwise operator.

59
© 2018 by Innovation In Software Corporation
SIZE OF INT
Get the size of the int type for
package main

your implementation using the import "fmt"

Sizeof method, which is in the import "unsafe"

unsafe package. func main() {

var i int = 1

fmt.Printf("Size of i is: %d",


unsafe.Sizeof(i))

60
© 2018 by Innovation In Software Corporation
WANT SOMETHING BIG
Do you need a bigger version of an
integer or float? You will find it in
math/big package.
The big package contains the types Int
and Float, which as essentially
unlimited in type. Using these types is
an effective way to avoid overflows.
You can cast between int and float64
to big versions (i.e., Int and Float)
using the NewInt and NewFloat
functions respectively.
Note: using big types to avoid
unknown overflows is not
recommended.

61
© 2018 by Innovation In Software Corporation
package main

WANT SOMETHING BIG - 2 import (


"fmt"
"math"
"math/big"
)

// (Public) Returns F(n).


func main() {

fmt.Println(mul(big.NewInt(math.MaxInt64),
big.NewInt(math.MaxInt64)))
}

func mul(x, y *big.Int) *big.Int {


return big.NewInt(0).Mul(x, y)
}
func sub(x, y *big.Int) *big.Int {
return big.NewInt(0).Sub(x, y)
}
func add(x, y *big.Int) *big.Int {
return big.NewInt(0).Add(x, y)

62
}
© 2018 by Innovation In Software Corporation
BITWISE OPERATORS
Operator Description

^ Bitwise complement: ^L

& Bitwise And: L1 & L2

| Bitwise Or: L | R

^ Bitwise Xor: L ^ R

&^ Bitwise clear: L &^ R

<< Left shift: L << R

>> Right shift: L >> R

… Compound operators

63
© 2018 by Innovation In Software Corporation
POP QUIZ: WHAT IS THE RESULT?

package main

import "fmt"

func main() {

i := 10 // 1010
j := i >> 1 // 0101

k := i | j // 1111

fmt.Println("j", j, "k", k)

10 MINUTES

64
© 2018 by Innovation In Software Corporation
FLOAT
Floating point data is stored in IEEE-754 format.
https://en.wikipedia.org/wiki/IEEE_754
Unlike integers, there is no generic float type. You must use either
float32 or float64. The float64 type is the most common floating point
type.
When cast to an integer (i.e., int(f)), the fractional part of a float is
discarded or truncated. There is no rounding. You perform manual
rounding using the math.modf function, which returns the whole and
fractional parts.

65
© 2018 by Innovation In Software Corporation
CASTING
package main

import "fmt"

func main() {
var a = 12.55

Explicit casting is supported in var b = int(a)

the Go Language. Assuming a


var c = float64(b)
var d = []byte("test")

compatible type, you can cast var e = []rune("test")

using the type name. fmt.Println(a)


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

66
© 2018 by Innovation In Software Corporation
COMMENTS
Go Language supports
C++ style comments.
Single line comments are (
// ). This is a comment to
end of line. Multi-line
comments are ( /* */ ).
There are two philosophies
on commenting source
code: traditional versus
agile.

67
© 2018 by Innovation In Software Corporation
LANGUAGE BUILDING BLOCKS

68
© 2018 by Innovation In Software Corporation
KEYWORDS

break case chan

const continue default

defer else fallthrough

for func go

goto if import

interface map package

range return select

struct switch type

var

69
© 2018 by Innovation In Software Corporation
IDENTIFIERS
append bool byte
cap close complex
complex64 complex128 copy
delete error false
float32 float64 image
int int8 int16
int32 int64 iota
len make new
nil panic print
println real recover
rune string true
uint uint8 uint16
uint32 uint64 uintptr

70
© 2018 by Innovation In Software Corporation
INTERESTING

71
© 2018 by Innovation In Software Corporation
CONSOLE READ

72
© 2018 by Innovation In Software Corporation
BUFFER READ
package main

import (
"bufio"
"fmt"
"os"

You can read from the )


// This is not perfect code!

console using a stream, func main() {

which can be stdin (i.e.,


reader := bufio.NewReader(os.Stdin)
for {

console / terminal). fmt.Print("Enter text: ")


text, _ := reader.ReadString('\n')
fmt.Println(text)
if len(text) == 2 {
print("done")
break
}
}
}

73
© 2018 by Innovation In Software Corporation
SCAN FUNCTIONS
package main
Scanln defaults to reading import (

from the console / "fmt"

terminal. Empty reads do


)

func main() {

not leave residual for {

characters in the input var s string


fmt.Print("Enter text: ")

variable. fmt.Scanln(&s)
fmt.Println(s)
if len(s) == 0 {
print("done")
break
}
}
}

74
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Lab 3 – Guess number

75
THE GAME
User gets 5 guesses at a number. Here are the steps of the Guessing
Number game:
1. Prompt and then enter number to guess ( < 100 )
2. Prompt for guess
3. Enter guess
4. If correct, end game. List number of guesses and congratulations.
5. After 5th incorrect guess:
A. Display correct number
B. Display game over message
C. End game
6. Display “high” or “low” depending on guess
7. Go to Step 2

76
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

CONTROL
if, for, switch, and panic
BRANCHING
Branching and arcs are necessary for real world applications. Top-
down programming is not practical in all scenarios. However, too
much reliance on branching can add to the complexity of your
application.
Go has the basic control structures, such as the if and for statement.
However, some common control elements are missing:
• while
• do..while
• ternary operator

78
© 2018 by Innovation In Software Corporation
IF STATEMENT

package main
The if statement evaluates a bool
expression. If true, the if block is done. import "fmt"

If false, the if block is not done. func main() {

Here is the syntax: a := 5


if optionalStatement; booleanExpression { if a++; a > 4 {
optionalStatements fmt.Println(a)

} }
}

79
© 2018 by Innovation In Software Corporation
IF ELSE STATEMENT
The if statement evaluates a bool package main

expression. If true, the if block is import "fmt"

done. If false, the else block is func main() {


performed. a := 5

Here is the syntax: if a++; a > 10 {


fmt.Println(a)
if optionalStatement; booleanExpression {
} else {
optionalStatements fmt.Println("cool!")
} else { }

optionalStatements }

80
© 2018 by Innovation In Software Corporation
IF ELSE IF STATEMENT
package main

import "fmt"

func main() {
a := 5

b := 10

if a > b {

fmt.Println("a")

The if else if construct is a nested if }

statement. The construct is more


if b > a {

fmt.Println("b")
efficient and cleaner than a series of }

mutually exclusive if statements. if b == a {

fmt.Println("a equal b")

// Alternative
if a > b {

fmt.Println("a")

} else if b > a {

fmt.Println("b")

} else {

fmt.Println("a equal b")

81
}
© 2018 by Innovation In Software Corporation
SWITCH STATEMENT
Switch statements switch on a value The syntax for a expression switch is:

where execution jumps to a matching


statement. Expression switches switch
switch optionalStatement; valueExpression {
case expressioncommalist1:
on an expression, including string optionalStatements
expressions. case expressioncommalistn:

• There is no automatic fall through optionalStatements

between switch statements. default:


optionalStatements
• The default statement is the else }

statement of the switch


.

82
© 2018 by Innovation In Software Corporation
SWITCH STATEMENT - 2
package main

import "fmt"

func main() {

val := "str"

switch val {

case "test":

fmt.Println("no")

Here are a couple of examples of case "str":

expression switches.
fmt.Println("good")

val2 := true

switch val2 {

case true:

fmt.Println("true")

case false:

fmt.Println("false")

default:

fmt.Println("impossible!")

83
}
© 2018 by Innovation In Software Corporation
SWITCH WITH EXPRESSIONS
package main

import (
"fmt"

You use expressions as a case in


)

a switch block. They do not


func main() {

have to be constant. a := 5
b := 10

val := 9
b--
switch val {
case a:
fmt.Println(a)
case b:
fmt.Println(b)
case a + b:
fmt.Println(a + b)
}
}

84
© 2018 by Innovation In Software Corporation
SWITCH CONTINUATION
package main

import "fmt"

func main() {
const (

Critical = iota

By default, you do not Error

continue between cases Warning

within a switch statement,


)
val := Critical

such as in C++. You explicitly switch val {


continue to the next case case Critical:

statement with the fmt.Println("Critical")

fallthrough keyword. See the fallthrough

opposite code.
case Error:

fmt.Println("Error")

fallthrough

case Warning:

fmt.Println("Warning")

85
© 2018 by Innovation In Software Corporation
TYPE SWITCH
Type switch statements switch on a The syntax for a type switch is:

type value where execution jumps to a


matching statement. The type value
switch optionalStatement; typeExpression.(type) {
case typecommalist1:
should be of interface {} type. optionalStatements

• There is no fall through between case typecommalistn:

switch statements. optionalStatements


default:
• The default statement is the else optionalStatements
statement of the switch }

Interface {} discussed in a later


module.
.

86
© 2018 by Innovation In Software Corporation
TYPE SWITCH - 2 package main

import "fmt"
type MyStruct struct {
a int
b int
}

func main() {
xyz MyStruct

var val interface{} = xyz

Here is an example of the type switch. val.a=5 /// error!!!

switch val.(type) {
case string:
fmt.Println("string")
case int, int16, int32, int64:
fmt.Println("int")
}
case MyStruct:

87
© 2018 by Innovation In Software Corporation
FOR LOOP
There are several syntaxes in the Go Language for the for loop.
Here are the various syntaxes:
for {
// infinite loop
optionalStatements
}

for optionalPrestatement; boolExpression; optionalPostStatement {


// C style for loop
optionalStatements
}

for booleanExpression {
// while loop
optionalStatements
}

for index, value:=range collection {


// iteration
}

88
© 2018 by Innovation In Software Corporation
BREAK / CONTINUE
The break statement terminates a for, switch, or select
statement.
The continue statement continues to the next iteration of a
for loop.

89
© 2018 by Innovation In Software Corporation
EXCEPTIONAL EVENTS

90
© 2018 by Innovation In Software Corporation
WHY DOES GO NOT HAVE EXCEPTIONS?
We believe that coupling exceptions to a control structure, as in the try-
catch-finally idiom, results in convoluted code. It also tends to encourage
programmers to label too many ordinary errors, such as failing to open a
file, as exceptional.
Go takes a different approach. For plain error handling, Go's multi-value
returns make it easy to report an error without overloading the return
value. A canonical error type, coupled with Go's other features, makes
error handling pleasant but quite different from that in other languages.
Go also has a couple of built-in functions to signal and recover from truly
exceptional conditions. The recovery mechanism is executed only as part
of a function's state being torn down after an error, which is sufficient to
handle catastrophe but requires no extra control structures and, when
used well, can result in clean error-handling code.

91
© 2018 by Innovation In Software Corporation
DEFER
The defer statement defers the package main

execution of a function or method import "fmt"


until the surrounding function or
func main() {
method is preparing to exit. The defer
method is called before the return defer fileCleanup()
defer releaseConnections()
results have been evaluated.
fmt.Println("in main...")
You can have more than one defer }

statement. They are execute Last In func fileCleanup() {


First Out (LIFO). fmt.Println("doing file cleanup")
}
In the defer function or method
perform cleanup that must be func releaseConnections() {

completed in all circumstances, such


fmt.Println("releasing connection")
}
as closing a file.

92
© 2018 by Innovation In Software Corporation
PANIC / RECOVER
Exception handling in the Go Language uses the panic and
recover functions.
The idiomatic way for handling known problems is to return
an error type as the sole value or one of many return values
(typically the error code is the last value).
Your program should handle known problems gracefully. Exceptions,
as unexpected events, use the panic function.
Call the recover function in a defer method to suppress a pending
panic. In the deferred method, you should take the opportunity to log
the error and implement a remedy.

93
© 2018 by Innovation In Software Corporation
PANIC / RECOVER - 2
Call the panic method to essentially throw an exception.
1. Execution in the current function immediately stops
2. Deferred methods in functions are called
3. Panic walks the call stack
4. The stack walk ends when a recover function is located on
the call stack
5. If no recover is found, the program is eventually
terminated.

94
© 2018 by Innovation In Software Corporation
PANIC / RECOVER - 3
package main func funcA() {

import "fmt" defer defer2()


funcB()
func main() {
}
funcA()
fmt.Println("finishing...") func defer1() {

} fmt.Println("defer1")
func funcC() { }
fmt.Println("funcC")
panic("Error!") func defer2() {
s := recover()
}
fmt.Println("recovered from", s)
func funcB() { }
defer defer1()
funcC()
}

95
© 2018 by Innovation In Software Corporation
CHECKING FOR A SPECIFIC EXCEPTION
You can check for a specific error versus suppressing all errors.
Check the error message to determine the error. Handling
unknown errors can pose a risk.
The recover function returns the error object as an interface {}.
For that reason, you do not have access to the error interface
and the Error function, which returns the string message. Use
type assertion to cast to the appropriate type.
If error not handled, repanic the error to continue up the call
stack.

96
© 2018 by Innovation In Software Corporation
SPECIFIC EXCEPTION - EXAMPLE
package main
import (

"fmt"

"os"

)
func main() {
defer func() {

err := recover()

var message = err.(error).Error()

if message == "runtime error: index out of range" {

fmt.Fprintf(os.Stderr, "Exception handled\n")

} else if message != "" {

fmt.Fprintf(os.Stderr, "Unplanned Exception: %v\n", message)

panic(err)

} else {

fmt.Fprintf(os.Stderr, "Exception unknown\n")

panic(err)

}()
//panic(errors.New("test"))

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

stuff[6] = 12
}

97
© 2018 by Innovation In Software Corporation
ERROR NEW
Many functions return an error type.
Error types adhere to the Error func Sqrt(f float64) (float64, error) {
interface which is: if f < 0 {
type error interface { return 0, errors.New(
Error() string "math: square root of negative number")
} }

// implementation

You can create an instance of the error return 0, nil

object using the errors.New function. }

The function accepts a string and


returns and error object.

98
© 2018 by Innovation In Software Corporation
CUSTOM ERROR TYPE

package net

You can create a custom error


interface by inheriting the type Error interface {

error interface and adding error

whatever is necessary. For a


Timeout() bool // Is the error a timeout?

network error, might include


Temporary() bool // Is the error temporary?

a timeout attribute method.

99
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Lab 4 – Factorial

100
CALCULATE FACTORIALS
A factorial is the product of multiplying successful values. For
example, 5! is 1*2*3*4*5. The result is 120.
Create an application that generates a factorial using a for loop. Read
the factorial from the command line and then calculate and display
the results.

101
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Collections
arrays, slices, and maps
ARRAYS
Arrays in the Go Language are a fixed length mutable collection of
elements of the same type. You can create either single- or multi-
dimensional arrays.
Elements of an array are accessible via the index operator ( [] ). Treat
index as an offset from the beginning of the array. The first element
of the array is located at index 0.
There are various syntaxes for declaring an array:

[length] type
[length] type { value1, value2, valuen}
[…] type { value1, value2, valuen}

103
© 2018 by Innovation In Software Corporation
ARRAYS - 2
package main

import "fmt"

var a1 [5]int
var a2 = [5]int{1, 2, 3, 4, 5}
var a3 = [...]int{1, 2, 3, 4, 5}
var a4 = [2][3]int{{1, 2, 5}, {3, 8, 4}}

Sample code for creating func main() {

and manipulating arrays. fmt.Println(a1)


fmt.Println(a2)

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

104
© 2018 by Innovation In Software Corporation
FOR LOOP

package main

import "fmt"

func main() {

You can iterate arrays a1 := [...]int{11, 12, 13, 14, 15}

using a for..range loop. for a, b := range a1 {


fmt.Println(a, b)
. }
}

105
© 2018 by Innovation In Software Corporation
SLICES
A slice is a variable-length fixed capacity collection containing
elements of the same type. Slices can be shrunk by slicing or enlarged
using the append function. Every slice has an underlying hidden
array. You can create multi-dimensional slices by assigning slices to
slices.
Using the interface type interface {} , you can actually store anything in
a slice or array.
Here are methods to create a slice:
make([] type, length, capacity)
make([] type, length)
[] type {}
[] type {value1, value2, valuen}

106
© 2018 by Innovation In Software Corporation
SLICES - 2
package main

import "fmt"

var a1 = make([]int, 5, 10)


var a2 = []int{1, 2, 3, 4, 5}
var a3 = [][]int{{1, 2, 5}, {3, 8, 4}}
Sample code for creating and
manipulating slices. func main() {
fmt.Println(a1)

. fmt.Println(a2)
fmt.Println(a3)
}

107
© 2018 by Innovation In Software Corporation
SLICE OPERATIONS

Operation Description

s[n] Return item at index


Slice operations can be s[n:m] Slice from n to m-1
applied to either arrays or s[n:] Slice from n to end

slices. Here are the slice s[:m] Slice beginning to m-1

operations. s[:] Slice from beginning to end

cap(s) Return the capacity

len(s) Return the length

108
© 2018 by Innovation In Software Corporation
SLICE OPERATIONS - 2 package main

import "fmt"

func main() {
myslice := []int{1, 2, 3, 4, 5, 6}

a := myslice[4]

b := myslice[2:4]

c := myslice[2:]

d := myslice[:4]

e := myslice[:]

fmt.Println(a)

fmt.Println(b)

fmt.Println(c)

fmt.Println(d)

fmt.Println(e)
}

109
© 2018 by Innovation In Software Corporation
APPEND OPERATIONS
package main 1
an executable (1)
import "fmt" 2
import fmt package (2)
func main() {

create a slice of six integers (3) myslice := []int{1, 2, 3, 4, 5, 6} 3

myslice2 := []int{20, 21, 22} 4


create a slice of three integers (4)
a := append(myslice, 7, 8, 9) 5

append three elements to a slice(5)


b := append(myslice, myslice2...) 6

append a slice (6) c := append(myslice, myslice2[:2]...) 7

fmt.Println(a)
append a partial slice (7)
fmt.Println(b) 8
display results (8)
fmt.Println(c)
}

110
© 2018 by Innovation In Software Corporation
SORT OPERATIONS
Operation Description

Float64(fs) Sorts []float64 in ascending order


You can sort slices based on
type, such as sorting an int slice.
Float64sAreSorted(fs) Returns true if []float64 is sorted

Sort operations are naturally


Ints(is) Sorts []int in ascending order

located in the sort package.


IntsAreSorted(is) Returns true if []int is sorted

Here are the basic sort


SearchFloat64s(fs, f) Returns index position of f in fs

operations. SearchInts(is, i) Returns index position of i in is

SearchStrings(ss, s) Returns index position of s in ss

Strings(ss) Sorts []string in ascending order

StringsAreSorted(ss) Returns true if []string is sorted

111
© 2018 by Innovation In Software Corporation
SORT OPERATIONS - 2

package main

import "fmt"
import "sort"

func main() {
myslice := []int{11, 2, 31, 4, 15, 6}

sort.Ints(myslice)

fmt.Println(myslice)

fmt.Println(sort.IntsAreSorted(myslice))
}

112
© 2018 by Innovation In Software Corporation
MAPS
Maps in Go Language are an unordered collection of key, value pairs where the keys are
unique. The key should support the == and != operators. Most notably, slices cannot be
used as keys.
Map keys must be of the same type. You can store any type as a map value using the
interface{} type.
Maps are reference types.
There are various methods to create a map:
make(map[keyType] valueType, initialCapacity)
make(map[keyType] valueType)
map[keyType] valueType{}
map[keyType] valueType {key1:value1, key2:value2, keyn:value2}

113
© 2018 by Innovation In Software Corporation
MAP BEHAVIOR
Maps support various behaviors:
• Add a key, value
map[key]=value
• Change a value
map[key]=value
• Delete a value
delete(map, key)
• Get a map value
value=map[key]

114
© 2018 by Innovation In Software Corporation
MAP EXAMPLE
package main

import "fmt"

func main() {
teams := map[string]int{"basketball": 5,
"football": 11, "baseball": 9}

teams["hockey"] = 11

delete(teams, "football")

for team, players := range teams {


fmt.Println(team, players)
}

115
© 2018 by Innovation In Software Corporation
NIL SLICES

It is okay to add elements to a var fslice []float64

nil slice with the exception of a fslice = append(fslice, 1.0)

map slice. For a map slice, fmt.Println(fslice)

adding elements to a nil


instance will cause a panic to be
var mymap map[string]int
mymap["test"] = 1
raised.
.

116
© 2018 by Innovation In Software Corporation
CAP AND MAPS

var2 := make(map[string]int, 9)
You cannot use the cap fmt.Println(cap(var2))
function with maps – even if the
capacity is specified. var3 := make([]int, 5, 10)
fmt.Println(cap(var3))
.

117
© 2018 by Innovation In Software Corporation
SEMICOLON RULE
When listing the elements of a composite literal, the elements, even the last member,
should conclude with a comma. This is part of the semicolon rule.

Semicolon Rule
Like many languages Go Language statements have a semi-colon terminator, which is
inserted implicitly. The lexer adds the semi-colon.
Like C, Go's formal grammar uses semicolons to terminate statements, but unlike in C,
those semicolons do not appear in the source. Instead the lexer uses a simple rule to insert
semicolons automatically as it scans, so the entered text is mostly free of them.
If the go statement concludes with a token before a linefeed, a semi-colon is implicitly
added as the terminator.
You can add semicolons to separate statements on a single line of source code.

118
© 2018 by Innovation In Software Corporation
SEMICOLON RULE - 2
You must insert semicolons manually when placing more than one statement
on a line and inside a simple for loop.

for i := 0; i < 5; i++ {


fmt.Println(i)
}

One effect of semicolon insertion is that an opening brace cannot be alone


on a single line.

119
© 2018 by Innovation In Software Corporation
POP QUIZ: WHY IS THE FINAL COMMA NECESSARY?

var m4=map[string] int {


"a":1,
"b":2,
}

5 MINUTES

120
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Lab 5 – AIRPORT

121
AIRPORT ITINERARY
Airportc Code
Atlanta ATL
Beijing PEK
Create a map of airport codes. As a Chicago ORD
command prompt, accept a airport London LHR
itinerary (airport codes) as command Tokyo HND
arguments and display the trip. Try Los Angeles LAX
these itineraries: Paris CDG
Dallas DFW
BKK LAX JFK Frankfurt FRA
Denver DEN
LHR ATL ORD
Hong Kong HKG
SIN LA DFW Madrid MAD
Dubai DXB
For example, “BKK LAX JFK” would New York JFK
return: Amsterdam AMS
Bangkok to Los Angeles to New York Jakarta CGK
Bangkok BKK
Make sure program has error Singapore SIN
detection. Guangzhou CAN
Shanghai PVG

122
© 2018 by Innovation In Software Corporation
AIRPORT CODES
You can copy the airport codes from a number of websites online, such as.
http://www.nationsonline.org/oneworld/major_world_airports.htm

123
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Functions
procedure, functional, anonymous

124
FUNCTIONS
Functions are a fundamental building block in most languages. This is
the bedrock of procedural and modular programming. In Go
Language, functions are first class citizens and can be used as
variables, parameters, and return values.
Here is the syntax for a function.
func functionName(optional parameters) optional return type {
body
}

func functionName(optional parameters) (optional return types) {


body
}

125
© 2018 by Innovation In Software Corporation
FUNCTIONS EXPLAIN - PARAMETERS
A function has zero or more
package main

parameters. If more than one import "fmt"

parameter, provide a comma func main() {


separated list.
funcA(5, "cool")

• For variadic functions, the last funcB(5, true, false, false)

function parameter is ellipses (…). }

The parameter is passed into the func funcA(a int, b string) {


function as [] type. Variadic fmt.Println(a, b)

functions have a variable length }

parameter list. func funcB(a int, b ...bool) {

. fmt.Println(b)

126
© 2018 by Innovation In Software Corporation
FUNCTIONS EXPLAIN – RETURN VALUES
A function can return zero or more values. If more than one
return value, provide a comma separated list within parentheses
“()”.
• The return values can be either named or unnamed; but not a
mixture.
• If unnamed, all return values must be specified.
• For named, all returns values do not have to be present.
• Functions that have a return value must have at least one
return statement or call panic as the final statement.
.

127
© 2018 by Innovation In Software Corporation
FUNCTIONS EXPLAIN – RETURN VALUES - 2
package main func funcC() (a int, b int) {

a = 12
import "fmt"
b = 18

func main() { return a, b

}
fmt.Println(funcA())

fmt.Println(funcB()) func funcD() (a int, b int) {

fmt.Println(funcC()) a = 20

fmt.Println(funcD()) b = 30

fmt.Println(funcE()) return

fmt.Println(funcF()) }
}
func funcE() (a int, b int) {
func funcA() int {
a = 12
return 5
b = 18
}
return b, a

}
func funcB() (int, int) {

return 5, 10
func funcF() (a int, b int) {
}
a = 12

128
b = 18

}
© 2018 by Innovation In Software Corporation
POP QUIZ: DOES THIS COMPILE?

func doesThisWork() int {

if true {
return 5
}
}

5 MINUTES

129
© 2018 by Innovation In Software Corporation
RESERVED FUNCTIONS
The Go Language reserves two function names: init and main. Both
are called automatically and should not be called directly. The init and
main functions should have no parameters or return values.
The init function is optional; but the main function is required for an
executable. Here is the order of invocation:
1. The init function is called on each imported packaged first
2. If several imported packages, init functions are called in textual
order.
3. The init function is called in the executable.
4. The main function is called in the executable.

130
© 2018 by Innovation In Software Corporation
EXIT
Call the Exit function in the os package to immediately exit a Go
Language program and return a status.
Note: defer methods will not be called. For that reason, only use
os.Exit in critical situations.
If running the application from the command prompt, go run will
display the exit code.

131
© 2018 by Innovation In Software Corporation
CLOSURES
Anonymous functions are closures. They are also called function
literals. Closures are a great solution where a function is used at one
location. You can also use closures to initialize function parameters,
return values, and more.
Closures capture constants and variables available at the scope where
it is created; but only if it references them. This occurs even if the
constant or variable is out of scope before the closure executes.
Closures are defined as a regular function but without a name.
From other languages, closures are similar to a lambda or function
pointer.

132
© 2018 by Innovation In Software Corporation
CLOSURES - 2
declare local variables (1)
package main

import "fmt"

declare closure and assign to a variable (2a) func main() {

a := 5

closure captures two variables: a, b (2a)


1
b := 10

x := func() int {

execute closure (3) return a * b 2

fmt.Println(x()) 3
create and execute closure in-place (4) fmt.Println(func() int {
4
return 42
}())
}

133
© 2018 by Innovation In Software Corporation
GENERIC FUNCTION
Languages, such as Java and // C++ code

C++, support generic or


templated functions. Go
template <class T>

Language does not have this


void swap(T& x,T& y)
{
feature. T temp;

In C++, the templated swap


temp=x;

function can be called with


x=y;
y=temp;
various types and prevents }

redundant code, which is of


course is a bad practice.
How is this done indirectly in
the Go Language?

134
© 2018 by Innovation In Software Corporation
GENERIC FUNCTION - 2
package main

Using the interface type, import "fmt"

you can create something


import "reflect"

func main() {

similar to a generic a, b := swap(10, 5.4)

method. Be warned – this


c, d := swap("dog", "cat")

fmt.Println("a", a, "b", b)

is potentially unsafe. An }
fmt.Println("c", c, "d", d)

empty interface is the func swap(first interface{},

anything type in the Go


second interface{}) (interface{},
interface{}) {

Language. Similar to the


ft := reflect.TypeOf(first).Kind()
st := reflect.TypeOf(second).Kind()

object type in C# or Java. if ft != st {


return nil, nil
}

return second, first


}

135
© 2018 by Innovation In Software Corporation
FUNCTION POINTERS
package main

You can declare a function import "fmt"

pointer with the type import "os"

keyword. The resulting type fptr func(int) int

function type can be used to func main() {

define variable, parameter, if len(os.Args) == 1 {

and return types. Similar funcExecute(double)

functions can be defined by


} else {
funcExecute(triple)

the function variable. }


}

When initialized, you can func double(a int) int {

invoke a function through a


return a * a
}

function pointer using the func triple(a int) int {

call operator “()”. }


return a * a * a

func funcExecute(f fptr) {


fmt.Println(f(5))

136
}

© 2018 by Innovation In Software Corporation


SCOPE
Scope defines where a
package main

variable is visible. Variables


import (
"fmt"

are either global or local. )

Local variables can hide a var i = 5

global variable that has the func main() {

same identifier. The local i := 4.5

variable is a shadow {

variable when this occurs. i := "test"


fmt.Println(i)
}
fmt.Println(i)
}

137
© 2018 by Innovation In Software Corporation
SELECT STATEMENT
In the Go language, coroutines are equivalent to threads and are asynchronous
function calls. Every program has a primary thread, where main is the entry point.
A coroutine is a separate and parallel path of execution starting at the provided
function.
As a form of interthread communication, threads can communicate with each
other via channels.
You can block and wait on communication via a select statement. A select block is
similar to a switch block except:
• You are switching on channels
• The select statement will block waiting for data in the channel
Note: Threading is a major topic and something covered in depth in the advanced
class.
This slide is just to introduce select as the other transfer of control statement.

138
© 2018 by Innovation In Software Corporation
SELECT STATEMENT - EXAMPLE
package main
for i := 0; i < 2; i++ {
import ( select {
"fmt"
case message1 := <-channel1:
"time"
fmt.Println("Channel1", message1)
)
case message2 := <-channel2:
func main() { fmt.Println("Channel2", message2)

}
channel1 := make(chan string)
channel2 := make(chan string) }

go func() {
time.Sleep(2 * time.Second)
channel1 <- "go routine1"
}()
go func() {
time.Sleep(4 * time.Second)
channel2 <- "go routine2"
}()
}

139
© 2018 by Innovation In Software Corporation
FUNCTION OVERLOADING
package main

import (
"fmt"
)
GO Language does not support
function overloading. func FuncA() {

func FuncA(a int) {


fmt.Println(a)
}

func main() {

FuncA(5)
}

140
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Lab 6 – MATRIX

141
MATIX OPERATIONS
Create an array of functions that represent math operations that
return double types. Each takes two parameters and returns the
result.

Operations Param 1 Param 2 Answer


Addition a 4 5 ?
Division d 0 3 ?
Multiplication m 4 8 ?
Subtraction s 1 4 ?

Perform each operation (row) in the most efficient way. When


completed, display the results.

142
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Strings
slices, characters, and bytes

143
STRINGS
Go Language supports Unicode strings. Strings in Go Language are
also immutable. Strings are slices and the slice operations apply.
When using the Append function, the target string may change and
not be replaced. As with an slice, this depends on the capacity of the
underlying array.
Go Language provides substantial support for string manipulation.
There several standard methods but also additional functionality in
several packages, especially the Strings, Strconv, and Unicode
packages.
Strings default to an empty string; not a nil string.

144
© 2018 by Innovation In Software Corporation
STRING EXAMPLE
package main fmt.Println(hello[index-1])
temp := hello[index-1]
import (
fmt.Printf("string: \"%s\":\n", temp)
"fmt"
fmt.Println("index rune char bytes")
"os"
for index, char := range temp {
"strconv"
) fmt.Printf("%-2d %U '%c' %X\n",
index, char, char,
var hello = []string{"Hello", "Hola",
[]byte(string(char)))
"Bon Jour", "Ciao", "こんにちは"}
}

func main() { }

var index = 1
if len(os.Args) > 1 {
index, _ = strconv.Atoi(os.Args[1])
}
if index < 1 || index > len(hello) {
index = 1
}

145
© 2018 by Innovation In Software Corporation
STRING EXAMPLE - 2

146
© 2018 by Innovation In Software Corporation
UNICODE
Unicode is a multiple byte character set. There is a codepoint (rune)
for each character around the world. The code points range from
0x0 to 0x10FFFF, which is also unicode.MaxRune.
Unicode is supported by various character encodings. UTF-8 is the
most popular of those encodings and used by Go Programming.
UTF-8 uses one byte for the first 128 code points and up to four
characters for the remaining code points.
Because of the mixed character lengths, the challenge with UTF-8 is
getting the length or byte location within a string.
In Go Language, each code point is called a rune which is
synonymous with a int32.

147
© 2018 by Innovation In Software Corporation
STRINGS AS BYTES
You can convert between
package main

strings and something else:


import "fmt"

func main() {
str := "नमस्ते"
• String to bytes
bytes := []byte(str)
fmt.Println(bytes)
• Bytes to string
• Strings to rune
str2 := string(bytes)
fmt.Println(str2)

runes := []rune(str)
fmt.Println(runes)
• Rune to strings
str3 := string(runes)
fmt.Println(str3)
• Strings to characters
}

148
© 2018 by Innovation In Software Corporation
STRINGS AS BYTES - 2

149
© 2018 by Innovation In Software Corporation
STRING LITERALS Escape sequence Description

\\ Backslash

Literals are defined within \000 Unicode character

quotes. Double quote is \” Single quote*

the interpreted literal. Back \’ Double quote*

ticks (`) are for raw string \a Bell

literals and multi-line \b Backspace

strings.
\f Formfeed

\n Linefeed

\r Carriage return

\t Tab

\uhhhh Unicode character

\v Vertical tab

\xhh Unicode character

150
© 2018 by Innovation In Software Corporation
STRING EXAMPLE
package main

import "fmt"

func main() {

fmt.Println("test1\t1\t2\ntest2\t3\t4\n")
fmt.Println(`test1\t1\t2\ntest2\t3\t4
.....
cool!`)
fmt.Println("\u3041")
fmt.Println("\x78")
}

151
© 2018 by Innovation In Software Corporation
STRINGS ARE SLICES
Strings are slices and sliced along bytes. For ASCII (lets say for
English strings), there is a one-to-one mapping. This makes accessing
ASCII strings straightforward. This however potentially poses a
challenge for other languages where character length is greater than
a byte.
There are two consistent options: convert string to a rune slice or
use these functions: strings.Index or strings.LastIndex.

152
© 2018 by Innovation In Software Corporation
STRING EXAMPLE
package main

import (
"fmt"
"strings"
)

var hello = "こんにちは "

func main() {

indexb := strings.Index(hello, "ん")


indexe := strings.LastIndex(hello, " ")
fmt.Println(hello[indexb:indexe])
}

153
© 2018 by Innovation In Software Corporation
STRING OPERATIONS
Operation Description
These are the standard string L1+=L2 Append string L2 to L1
operations. L1+L2 Concatenate L2 to L1

Strings are slices. All of the L1[n] Access nth raw byte

standard slice operations also L1[b:e] String from index b to e-1

apply to strings. L1[b:] String from index to end

The comparison operators for L1[:e] String from 0 to index

strings are: len(str) Number of bytes

len([] rune(L1)) Number of characters


<, <=, ==, ++, !=, >, and >= [] bytes(L1) Convert string to slice of
bytes
string([] byte) Convert [] byte to string

154
© 2018 by Innovation In Software Corporation
Operation Description

STRINGS PACKAGE
Contains(s, t) Returns true if t in s

Count(s, t) Count of t in s

EqualFold(s1, s2) Non case sensitive


equality
Fields(s) Returns string slice split
along whitespace
HasPrefix(s, t) True if s begins with t

HasSuffix(s, t) True if s ends with t

The strings package contains a myriad Index(s, t) Returns index of first t in s

of functions that are commonly used Join([] s, c) Joins strings with c


delimiter
for string manipulations. Here are LastIndex(s, t) Last occurrence of t in s
some of the prevalent functions. Repeat(s, i) Repeat s times i number
of times
ToLower(s) Convert string to
lowercase
ToUpper(s) Convert string to
uppercase
Trim(s, t) Trim t from either end of s

155
TrimSpace(s) Trim spaces from either
© 2018 by Innovation In Software Corporation end of s
STRINGS PACKAGE - 2
package main

import (
"fmt"
"strings"
)

func main() {

test := "String conversion"


test2 := []string{"one", "two", "three"}
fmt.Printf("1 - %d\n", strings.Count(test, "i"))
fmt.Printf("2 - %t\n", strings.HasPrefix(test, "Str"))
fmt.Printf("3 - %s\n", strings.Join(test2, " "))
fmt.Printf("4 - %s\n", strings.ToUpper(test))
}

156
© 2018 by Innovation In Software Corporation
STRCONV PACKAGE
Operation Description

Atoi(s) Convert string to int

FormatBool(b) Return “true” or “false”

FormatFloat(f, Return float as string


fmt, prec, bits)
FormatInt(i, Return int as a string
The strconv package has several base)

functions for converting to and from FormatUInt(u,


base)
Return uint as a string

strings. IsPrint(c) True if c is printable

Itoa(i) Convert int to string

ParseBool(s) Return s as bool

ParseFloat(s, bits) Return s as float

ParseInt(s, base, Return s as int


bits)
ParseUint(s, base, Return s as uint
bits)

157
© 2018 by Innovation In Software Corporation
STRCONV PACKAGE - 2
package main

import (
"fmt"
"strconv"
)

func main() {

x, _ := strconv.ParseFloat("120.21", 64)
fmt.Printf("%8T\t%5v\n", x, x)
y, _ := strconv.ParseInt("42", 10, 0)
fmt.Printf("%8T\t%5v\n", y, y)
z, _ := strconv.Atoi("42")
fmt.Printf("%8T\t%5v\n", z, z)
}

158
© 2018 by Innovation In Software Corporation
UNICODE PACKAGE
Operation Description

IsControl True if control character

IsDigit True if decimal digit

IsLetter True if letter

The Unicode package has a IsLower True if lowercase letter

variety of functions mostly to IsPrint True if printable character

confirm the status of a Unicode IsPunct True if punctuation


character
character. IsSpace True if whitespace
character
IsSymbol True if symbol character

IsUpper True if uppercase


character
ToLower Convert to lowercase
character
ToUpper Convert to uppercase
character

159
© 2018 by Innovation In Software Corporation
FORMAT COMMANDS
Operation Description

Errorf(format, Return error info


args…)
Fprint(writer, Write the args to a writer
args…) stream
Fprintf(writer, Write the args to a writer
The format commands are in format, args…) stream in the specified
format
the fmt package. Many of Fprintln(writer, Same as Fprintf but
args…) terminated with a linefeed
these functions have already Print(args…) Write args to stdout
been demonstrated. Some write Printf(format, Write the args to the
to stdout, a string, or stream. args…) stdout in the specified
format
Here are the more common Println(args…) Same as Println but
terminated with a linefeed
functions: Sprint(args…) Return a string consisting
of args
Sprintf(format, Return a string consisting
args…) of args in the specified
format
Sprintln(args…) Return a string consisting
of args terminated with a

160
linefeed
© 2018 by Innovation In Software Corporation
APPEND VERSUS JOIN
package main
The compound operation
import ( += is convenient for
"bytes"
"fmt"
combining strings. The
)
string.Join is often a better
func main() {
alternative for
performance. Writing into
strings := []string{"one", "two", "three", "four"}
var buffer bytes.Buffer

for _, valuestring := range strings { a byte buffer is another


}
buffer.WriteString(valuestring)
solution that may be
}
fmt.Println(buffer.String())
quicker.

161
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Lab 7- String functions

162
STRING FUNCTIONS
Create three string functions
Delete(string, c): remove all characters (c) from string. Return the
new string. Test with “now is the time for all good men and women”.
Remove the character ‘o’ and display results.
Spaces(string): removes spaces from string. Return the new string.
Test with “now is the time for all good men and women”. Display the
results.
Expansion(string, [] map): return string with map expansion. Map is
string:string. Find keys in string and substitute value. Return new
string. Test with “t i c.”. The map is t:this, i:is, c:cool.

163
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Structures
types, object oriented, composition

164
NEW APPROACH
The fathers of the Go Language
were not afraid to blow up
ingrained and well-established
patterns of behavior. That is
what makes the Go Language
so exciting. The triumvirate did
just that to object oriented
programming. It was a
demolition - destroying
traditional approaches in favor
of something entirely new.

165
© 2018 by Innovation In Software Corporation
TERMINOLOGY
Emblematic of the change in perspective is the change of
terminology in the Go Language as pertains to object oriented
concepts:
• No inheritance
• Class is type
• Instance is value
• Member functions is methods
• this is receiver
• Virtual methods is duck typing

166
© 2018 by Innovation In Software Corporation
INHERITANCE VERSUS COMPOSITION
At schools, books, and online, there has been a long standing bias
towards inheritance and against composition. This has led to archaic
solutions that are at best neither maintainable nor extensible.
Inheritance implies an “is a kind of” relationship between two types,
code reuse, and tight coupling. Composition implies an “is a part of”
relationship between two types, code reuse, and loose coupling. The
loose coupling often makes composition more maintainable and
extensible than a similar solution using inheritance. Composition is
also referred to as embedding or containment.
The contrast between the two alternatives is best highlighted with
the classic Employee example.

167
© 2018 by Innovation In Software Corporation
class Person {

C++ INHERITANCE };

Here is standard C++ code for


class Salaried : public Person {

inheritance. What is wrong with };

this code – especially for Fred? class Hourly : public Person {

What if Fred wanted a


promotion?
};

What if Fred decided to retire?


class Executive: public Person {

Is this truly a is a kind of


};

relationship? int main() {

Executive Bob;

Salaried Sally;

Hourly Fred;

168
return 0;

}
© 2018 by Innovation In Software Corporation
C++ COMPOSITION
class Person {
void SetEmployment(IEmployee *e);

Employee *pEmployed;

Here is the solution for the }

employee scenario using class IEmployee {

composition. There are a few };

benefits including.
class Salaried : public IEmployee {

• Lazy evaluation };

• Extensible class Hourly : public IEmployee {

};

• Interface driven . . . . .

int main() {

From a strategic perspective, Person Bob;

this solution can be fully Person Sally;

Person Fred;
implemented in Go Language.
return 0;

169
}

© 2018 by Innovation In Software Corporation


CUSTOM TYPES
You can define custom types with the type keyword. This is similar to
typedef in C / C++. Custom types are used in several ways:
• Structs
• Function pointers
• Improves readability
• Aliases
The syntax is:
type typename typeSpecification
• typename is the identifier
• typeSpecification indicates the type, such as struct, int, and so on.

170
© 2018 by Innovation In Software Corporation
CUSTOM TYPES - 2
package main

type Count int

Here is some sample code of type StringInt map [string] int

defining custom types and


type Fptr func(int) (int, int)

type MyStruct struct{

declaring values of that type. data1 int

Declaring a value for a custom


data2 int

type is the same syntax as a func main() {


standard type.
var a Count

var b StringInt

var c MyStruct

171
© 2018 by Innovation In Software Corporation
METHOD
A method is a function that is called on a custom type. The value of
the type is usually passed into the method.
The method signature is similar to a function with the addition of a
receiver:
func (receiver) identifier(parameters) return
The method can be called on a value of that type using the .dot
syntax. The value is implicitly passed into the method as the receiver.
The receiver can be passed by value or by pointer.

172
© 2018 by Innovation In Software Corporation
METHOD - 2 package main

import "fmt"

type MyStruct struct {


data1 int 1
define a custom type (struct) (1) data2 int

}
declare a method for the custom type (2)
func (s MyStruct) Add() int {

return s.data1 + s.data2


declare a method for the custom type (3)
2
}

create a value for the custom type (4) func (s MyStruct) Multiply() int {
3
return s.data1 * s.data2

}
call the method on the value (5)
func main() {

var c = MyStruct{5, 10} 4


fmt.Println(c.Add())
5

173
fmt.Println(c.Multiply())
}
© 2018 by Innovation In Software Corporation
POP QUIZ: WHAT IS THE RESULT?
package main

import "fmt"

type MyStruct struct {


data1 int
data2 int
}

func (s MyStruct) Increment() {


s.data1++
s.data2++
}

func main() {

var c = MyStruct{5, 10}


c.Increment()
fmt.Println(c)
}

10 MINUTES

174
© 2018 by Innovation In Software Corporation
POINTER TO RECEIVER
Unless otherwise stipulated, package main

receivers are passed by value into import "fmt"

a method. Therefore the method type MyStruct struct {

receives a copy of the receiver. data1 int

Changes made to the copy will not


data2 int
}

persist to the original receiver. func (s *MyStruct) Increment() {

Pass the receiver by pointer to s.data1++

change the original value.


s.data2++
}

Note: When the receiver is passed func main() {

by pointer, the method still uses var c = MyStruct{5, 10}

the dot syntax and not pointer


c.Increment()
fmt.Println(c)
notation. }

175
© 2018 by Innovation In Software Corporation
EMBEDDING
package main

import "fmt"

type Address struct {

street string

city string

You can embed a type inside a }


state string

struct. Embedded types are type Person struct {

unnamed. The affect is similar first string

to inheritance and the members


last string

Address

of the embedded value will be }

first class member values of the func main() {

outer type. var c Person = Person{"Bob", "Wilson",

Address{"200 Broad St", "Phoenix",

"AZ"}}

fmt.Println(c.street, c.city,

c.state)

176
}

© 2018 by Innovation In Software Corporation


package main

EMBEDDING - 2
import "fmt"

type Address struct {

street string

city string

state string

Methods on from embedded


}

type Person struct {

types are also available as first first string

class members of the last string

Address
surrounding custom type. }

Those methods can be called func (a Address) get() string {

directly on the surrounding return fmt.Sprintf("%s\n%s\n%s",

type. }
a.street, a.city, a.state)

func main() {

var c Person

177
fmt.Println(c.get())

}
© 2018 by Innovation In Software Corporation
package main

import "fmt"

METHOD OVERRIDING type Address struct {


street string
city string
state string
}

You can override methods type Person struct {

inherited from embedded


first string
last string

types. Simply implement the }


Address

same method on the func (a Address) get() string {

surrounding custom type. If return fmt.Sprintf("%s\n%s\n%s",


a.street, a.city, a.state)

wanted, you can in addition }

delegate to the overridden func (a Person) get() (string, string) {


return a.first + " " + a.last + "\n",

method using the fully qualified a.Address.get()

type.
}

func main() {

var c = Person{"Bob", "Wilson",


Address{"200 Broad St", "Phoenix",
"AZ"}}

178
fmt.Println(c.get())
© 2018 by Innovation In Software Corporation }
INTERFACES
An interface is a custom type that consists of method signatures. For
that reason, a interface is abstract. There is no implementation.
However, you can associate values with an interface. However, the
value must implement the methods of the interface. If not, a
compiler error will occur.
This is useful in limiting values passed a parameter, type of field,
return from a method or function, or membership in a collection.

179
© 2018 by Innovation In Software Corporation
INTERFACES - 2
package main
func (a Train) Start() {
type Vehicle interface {
Start() }
Turn()
func (a Train) Stop() {
Stop()
} }

type Auto struct {


func turnLeft(v Vehicle) {
}
}
func (a Auto) Start() {

func main() {
}
func (a Auto) Turn() {
var a Auto
var b Train
}
turnLeft(a)
func (a Auto) Stop() {
turnLeft(b)
}

}
type Train struct {
}

180
© 2018 by Innovation In Software Corporation
INTERFACE {}
Interface {} is a special interface that contains an empty set of
methods. Every value at a minimum has no methods. For that
reason, every value is an interface {} type. As an interface {} value,
you are limited. For example, you cannot call any methods on the
value. If necessary, the underlying methods can be accessed via type
assertion or type switch.
Interface {} is the ideal type when any type is acceptable or required
for a parameter, return, or member of a collection.

181
© 2018 by Innovation In Software Corporation
STRUCTURES
The Go Language supports C style structures.
Once defined, you can declare a value from a structure like any type.
Hard to make structures behave like a standard type. For example,
there is no operator overloading. Some consider operator
overloading to be syntactic candy anyway. You have to build out the
behavior of the structure using methods.

182
© 2018 by Innovation In Software Corporation
DUCK TYPING

In Go Programming, duck
typing is done with interfaces.
If a value implements a duck
interface, it must be a duck. All
other values that implement the
interface are also assumed to
be equally ducks. This may not
be true!

183
© 2018 by Innovation In Software Corporation
POLYMORPHISM
Duck typing is how polymorphism is implemented in the Go
Language. Polymorphism typically involves there four attributes:
• Related types
• Same methods
• Different behavior
• Derived pointer (or reference) to base class type
Duck typing can reasonably assure three of these four attributes.
Related types is not guaranteed however. This can lead to
interesting results.

184
© 2018 by Innovation In Software Corporation
DUCK TYPING EXAMPLE
func (Human) walk() {
fmt.Println("walking")
package main
}

import "fmt" func (Human) eat() {


fmt.Println("eating sushi")
type IPerson interface {
}
talk() func (Martian) talk() {
walk() fmt.Println("talking")
eat() }

}
func (Martian) walk() {
fmt.Println("walking")
type Human struct {
}
}
func (Martian) eat() {
type Martian struct { fmt.Println("eating Humans")
} }

func (Human) talk() { func invite2Party(partygoers ...IPerson) {

fmt.Println("talking") for _, person := range partygoers {


} person.eat()

185
}
}
© 2018 by Innovation In Software Corporation
BAD PARTY!

186
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Lab 8- Shapes

187
SHAPES
There goal of this lab is to draw a variety of shapes. Each shape is a type of
geometric object at a minimum able to draw themselves.
1. Define an interface iGeoshape with two methods: draw and print. The
methods have no parameters or return values.
2. Implement a custom Rectangle type. Define two methods for Rectangle:
draw and print. Stub both methods to display an appropriate message.
3. Implement a custom Circle type. Define two methods for Circle: draw
and print. Stub both methods to display a message.
4. Create a render function that accepts one parameter – a variable length
list of iGeoshape values. In the render function, call draw on each
iGeoshape value.

188
© 2018 by Innovation In Software Corporation
SHAPES - 2
5. In main, create values for three rectangles and two circles.
6. Call render function with the five values.

189
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Debugging
Walkthrough

190
WALKTHROUGH - DEBUGGING

This is a walkthrough of the


Delve debugger. Of course, the
delve debugger must be
installed. Here is the link again:
http://nanxiao.me/en/a-brief-
intro-of-delve/

191
© 2018 by Innovation In Software Corporation
DEBUG - DUCK TYPING EXAMPLE
func (Human) walk() {
fmt.Println("walking")
package main
}

import "fmt" func (Human) eat() {


fmt.Println("eating sushi")
type IPerson interface {
}
talk() func (Martian) talk() {
walk() fmt.Println("talking")
eat() }

}
func (Martian) walk() {
fmt.Println("walking")
type Human struct {
}
}
func (Martian) eat() {
type Martian struct { fmt.Println("eating Humans")
} }

func (Human) talk() { func invite2Party(partygoers ...IPerson) {

fmt.Println("talking") for _, person := range partygoers {


} person.eat()

192
}
}
© 2018 by Innovation In Software Corporation
WALKTHROUGH – START DEBUGGING
Start debugging:
dlv debug sample.go
The debugger will attached and
immediately stop the application.
This provides you an opportunity
to setup the debugging session.
Other helpful commands:
• Exit to quit
• Restart to start a new
debugging session

193
© 2018 by Innovation In Software Corporation
WALKTHROUGH – BREAKPOINTS
Setting breakpoints is typically
the first and most important
step in debugging. After
setting, you then can navigate
between breakpoints.
Set break with the breakpoint
command.
Breakpoints command will list
the breakpoints.

194
© 2018 by Innovation In Software Corporation
WALKTHROUGH – NAVIGATION
You can run the application
between breakpoints with the
continue command.
Other helpful commands:
• Step (step in)
• Next (step over)
• Stepout (step out)

195
© 2018 by Innovation In Software Corporation
WALKTHROUGH - STACK

Examining the stack is easy with


commands such as:
• Locals
• Args
• Regs

196
© 2018 by Innovation In Software Corporation
WALKTHROUGH – MARTIAN EATS

Let us restart the debugging


session. Now we want to break
only when the Martian eats!
ClearAll will clear the existing
breakpoints.

197
© 2018 by Innovation In Software Corporation
WALKTHROUGH – THREADS / VARIABLES

The threads and vars command


are often helpful in examining
an application.

198
© 2018 by Innovation In Software Corporation
WALKTHROUGH – THREADS

Changing the thread context is


often useful and affects
commands such as regs, locals,
args, list, and so on.
Use the thread command to
change thread context.

199
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Input / Output
Files

200
DATA RULES!
Data is the fuel for professional
applications. Hard to have a
sophisticated application
without data storage and
manipulation. The term “data”
can reference a variety of
resources, including file input-
output, JSON, STDIN, STDOUT,
TCP/IP, and even printing. Each
refers to a stream of
information flowing from a
source to a destination.

201
© 2018 by Innovation In Software Corporation
FILES
In the age of the internet, there
are still benefits of local files:
• Configuration files
• System files
• JSON
• XML files
• And more

202
© 2018 by Innovation In Software Corporation
FILE INPUT / OUTPUT
Import the io/ioutil package for access to the file input/output
functions. This package also includes functions for file and directory
manipulation and management.
• WriteFile: write bytes to a file
• ReadFile: read bytes to a file
You must convert data between bytes and another format when
necessary. When writing text for example, you need to convert
between bytes and string format.
WriteFile and Readfile is document based input / output where data
is transferred as a single instance.

203
© 2018 by Innovation In Software Corporation
FILE PERMISSIONS Permission Description

In Go, Unix permissions are 0000 No permissions

used for file permissions. There 0700 Read, write, and execute for owner

are three groups of 0770 Read, write, and execute for the
permissions: owner and the file group
0777 Read, write, and execute for

• The owner of the file 0111


everybody
Execute for everybody

• Anyone in the same group of 0222 Write for everybody


the file 0333 Write and execute for everybody

• Everyone else 0444 Read for everybody

Of course, setting correct 0555 Read and execute for everybody

permissions is essential for 0644 Read and write for the owner;
everyone else is read
proper application security. 0666 Read and write for everybody

0740 Read, write, and execute for

204
owner; read for the file group

© 2018 by Innovation In Software Corporation


WRITE FILE
package main

Use the WriteFile function to write import (

bytes to a file. "io/ioutil"

"log"
The syntax for the function is: )
func WriteFile(filename string, data
[]byte, perm os.FileMode) error func main() {

Here is sample code for writing text to s := "Hello, File!"

a file. Notice that the text is converted err := ioutil.WriteFile("hello.txt",

into bytes using []byte. []byte(s), 0644)


if err != nil {
log.Fatal(err)

205
© 2018 by Innovation In Software Corporation
WRITE FILE- EXPLAINED
package main
Import io/ioutil package (1)
import (
initialize string (2)
"io/ioutil" 1
"log"
write to hello.txt file (3)
)

convert string to bytes (3b) func main() {


s := "Hello, File!" 2

read / write permissions for the owner; everybody err := ioutil.WriteFile("hello.txt", 3


else is read (3c) []byte(s), 0644)
if err != nil {
4
if write operation fails, log err to stderr and exit the log.Fatal(err)
program (4)
}
}

206
© 2018 by Innovation In Software Corporation
READ FILE
package main

import (

Use the ReadFile function to read "fmt"

bytes from a file. "io/ioutil"


"log"

The syntax for the function is: )

func ReadFile(filename string) ( func main() {

[]byte, error) fileBytes, err := ioutil.ReadFile("hello.txt")

Here is sample code for reading text if err != nil {

from a file. Notice that bytes are


log.Fatal(err)
}
converted to a string using the string
function. fmt.Println(fileBytes)
fileString := string(fileBytes)
fmt.Println(fileString)
}

207
© 2018 by Innovation In Software Corporation
READ FILE- EXPLAINED
package main
Import io/ioutil package (1)
import (
read bytes from hello.txt file (2) "fmt"
"io/ioutil" 1

if write operation fails, log err to stderr (3) "log"


)

print file bytes (4) func main() {

fileBytes, err := ioutil.ReadFile("hello.txt") 2


convert bytes to a string (5) if err != nil {
log.Fatal(err) 3

print string (4) }

fmt.Println(fileBytes) 4
fileString := string(fileBytes) 5
fmt.Println(fileString) 6
}

208
© 2018 by Innovation In Software Corporation
READING AND WRITING STRUCTURES
Structures must be converted to and from bytes to read and write to
a file using the ReadFile and WriteFile functions respectively.
In the Json package, the Marshal and Unmarshal methods convert a
structure to and from bytes.
The syntax is:
func Marshal(v interface{}) ([]byte, error)
func Unmarshal(data []byte, v interface{}) error

These methods will use Json (JavaScript Object Notation) encoding.

209
© 2018 by Innovation In Software Corporation
WRITE STRUCTURE - EXAMPLE
func main() {
package main me := Person{
import ( Id: 1,
"encoding/json" Name: "Me",
"fmt" Age: 64}
"io/ioutil"
"log" b, err := json.Marshal(me)
)
type Person struct { fmt.Println(b, err)
Id int
Name string err2 := ioutil.WriteFile("hello3.bin",
Age int b, 0644)
} if err2 != nil {
log.Fatal(err)
}
}

210
© 2018 by Innovation In Software Corporation
READ STRUCTURE - EXAMPLE
package main func main() {
me := Person{}
import (
"encoding/json" fileBytes, err4 := ioutil.ReadFile("hello3.bin")
"fmt" if err4 != nil {
"io/ioutil"
"log" }

)
json.Unmarshal(fileBytes, &me)
fmt.Println(me)
type Person struct {
}
Id int
Name string
Age int
}

211
© 2018 by Innovation In Software Corporation
READING AND WRITING STRUCTURES (GOB)
You can also read and write structures using GOB, which is the Go
language serialization format. GOB data is self-describing. Pointers
are not serialized. However the data at the pointer is saved. The
effect is that the data is flatten as part of the serialization.

212
© 2018 by Innovation In Software Corporation
WRITE STRUCTURE (GOB) package main

The advantage to GOB is simplicity. To import (

serialize to a file: "encoding/gob"


"os"

• os.Create to get file handle )

• gob.NewEncoder to obtain a GOB type Person struct {

encoder Name string


Age int32
• gob.Encode to write stream to }
target resource func main() {

• Don’t forget to close the file filename := "buffer.gob"


bob := Person{"Bob Johnson", 35}
Here is the syntax:
file, err := os.Create(filename)
func Create(name string) (*File, error)
if err == nil {
func NewEncoder(w io.Writer) *Encoder
encoder := gob.NewEncoder(file)
func (enc *Encoder) Encode(e interface{}) error
encoder.Encode(bob)
}
file.Close()
}

213
© 2018 by Innovation In Software Corporation
package main

READ STRUCTURE (GOB)


import (
"encoding/gob"
"fmt"
"os"

To deserialize from a file to an object:


)

type Person struct {


• os.Create to get file handle Name string

gob.NewEncoder to obtain a GOB


Age int32
• }
encoder
func main() {

• gob.Decode to read stream into filename := "buffer.gob"

target object var bob = new(Person)


file, err := os.Open(filename)
• Don’t forget to close the file if err == nil {

Here is the syntax:


decoder := gob.NewDecoder(file)
err = decoder.Decode(bob)
func Create(name string) (*File, error) }

func NewEncoder(w io.Writer) *Encoder file.Close()

func (dec *Decoder) Decode(e interface{}) error if err != nil {


fmt.Println(err)
} else {
fmt.Println(bob.Name, "\t", bob.Age)
}

214
}

© 2018 by Innovation In Software Corporation


APPENDING TO A FILE
package main

import (
"os"
)

func main() {

filename := "hello.txt"
You cannot use io/ioutil package to f, err := os.OpenFile(filename,
append to a file. The ioutil functions are os.O_APPEND|os.O_WRONLY, 0600)
create as a convenience and kept simple. if err != nil {
For more complex io operations, use io panic(err)
package. }

defer f.Close()

text := "42"
if _, err = f.WriteString(text); err != nil {
panic(err)
}

215
}
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”

Packages
custom packages

216
PACKAGES
The Go Language provides a lot
of extra functionality through
third party packages available
at:
https://goperfd.appspot.com/
You can create your own
packages, executables or
libraries, that are shared with
others.

217
© 2018 by Innovation In Software Corporation
WHAT IS A PACKAGE
In this course, package have been single file applications. However,
that is not required. You can take a more modular approach.
Packages can be spread across multiple files that are in the same
directory. Just make the name of each package the same. For an
executable, the package files should start with “package main”.
Shared packages should be placed in a GOPATH source directory (i.e,
%gopath%\src. To avoid name conflicts, it is recommend to create
subdirectory for each unique package within the src directory.
Remember to indicate the hierarchal structure when importing the
package.

218
© 2018 by Innovation In Software Corporation
EXPORTED FUNCTIONS

Exported function names should package mypackage

start with an uppercase import "fmt"

character. Conversely, the initial


character of private methods are
// FuncA comment

lowercase. In addition, public


func FuncA() {
fmt.Println("FuncA")
methods should be commented. funcb()

Global cross package variables }

are similarly defined. func funcb() {


fmt.Println("funcb")
}

219
© 2018 by Innovation In Software Corporation
LOCAL PACKAGE
You can have a local or private library that is consumed only by your
applications.
Here are the steps:
1. In the application directory, create a subdirectory using the name of the
library package. If the library name is stuff.go, create a subdirectory
called stuff.
2. Copy the library into that directory.
3. The package command of the library should be:
package libraryname
4. In the client application, import the package as:
import “./libraryname”

220
© 2018 by Innovation In Software Corporation

You might also like