Introduction To Go Language Final PDF
Introduction To Go Language Final PDF
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.
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
Linux 2.6.23 or later with glibc amd64, 386, arm, arm64,s390x, ppc64le
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.
13
© 2018 by Innovation In Software Corporation
THE GO PLAYGROUND
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 (
"os"
“hello, world” application. "strconv"
func main() {
var index = 1
if len(os.Args) > 1 {
index, _ = strconv.Atoi(os.Args[1])
index=1
fmt.Println(hello[index-1])
23
}
© 2018 by Innovation In Software Corporation
HELLO.GO - EXPLAINED
package main 1
"fmt"
)
declare hello variable as a slice of strings(3) var hello = []string{"Hello", "Hola",
3
"Bon Jour", "Ciao", "こんにちは"}
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
}
24
© 2018 by Innovation In Software Corporation
SWAP.GO
package main
import "fmt"
by-pointer.
a := 5
b := 10
a, b = swap1(a, b)
fmt.Println(a, b)
swap2(&a, &b)
fmt.Println(a, b)
}
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() {
26
© 2018 by Innovation In Software Corporation
VARIADIC.GO
package main
import "fmt"
27
© 2018 by Innovation In Software Corporation
VARAIDIC .GO - EXPLAINED
package main 1
28
© 2018 by Innovation In Software Corporation
EMPLOYEE.GO
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
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 }
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
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))
variables.
type modifier func(string) string
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) }
34
© 2018 by Innovation In Software Corporation }
GETURL.GO package main
import (
"fmt"
"io/ioutil"
"net/http"
Go Language is multi-purpose and "os"
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() {
}
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)
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
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
/ Division: L1 / R1
% Remainder: L1 % R1
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"
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
var (
declare multiple variables of the same type (4) h = 10
5
i = "test"
48
© 2018 by Innovation In Software Corporation
SHORT VARIABLE DECLARATIONS
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
51
© 2018 by Innovation In Software Corporation
CONSTANTS
Constants are read only
package main
52
© 2018 by Innovation In Software Corporation
UNTYPED CONST
53
© 2018 by Innovation In Software Corporation
ENUMERATION
The Go Language does not support Enum const Bold = 1
54
© 2018 by Innovation In Software Corporation
BITWISE
package main
You can create a bitwise
enumeration using the bitwise
import "fmt"
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?
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
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
var i int = 1
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
fmt.Println(mul(big.NewInt(math.MaxInt64),
big.NewInt(math.MaxInt64)))
}
62
}
© 2018 by Innovation In Software Corporation
BITWISE OPERATORS
Operator Description
^ Bitwise complement: ^L
| Bitwise Or: L | R
^ Bitwise Xor: 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
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
for func go
goto if import
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"
73
© 2018 by Innovation In Software Corporation
SCAN FUNCTIONS
package main
Scanln defaults to reading import (
func main() {
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.”
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"
} }
}
79
© 2018 by Innovation In Software Corporation
IF ELSE STATEMENT
The if statement evaluates a bool package main
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")
fmt.Println("b")
efficient and cleaner than a series of }
// Alternative
if a > b {
fmt.Println("a")
} else if b > a {
fmt.Println("b")
} else {
81
}
© 2018 by Innovation In Software Corporation
SWITCH STATEMENT
Switch statements switch on a value The syntax for a expression switch is:
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")
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"
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
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:
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
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 booleanExpression {
// while loop
optionalStatements
}
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
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() {
} 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()
panic(err)
} else {
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
98
© 2018 by Innovation In Software Corporation
CUSTOM ERROR TYPE
package net
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}}
. 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() {
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"
. fmt.Println(a2)
fmt.Println(a3)
}
107
© 2018 by Innovation In Software Corporation
SLICE OPERATIONS
Operation Description
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() {
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
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")
115
© 2018 by Innovation In Software Corporation
NIL SLICES
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.
119
© 2018 by Innovation In Software Corporation
POP QUIZ: WHY IS THE FINAL COMMA NECESSARY?
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
}
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"
. 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
}
fmt.Println(funcA())
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?
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"
a := 5
x := func() int {
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
134
© 2018 by Innovation In Software Corporation
GENERIC FUNCTION - 2
package main
func main() {
fmt.Println("a", a, "b", b)
is potentially unsafe. An }
fmt.Println("c", c, "d", d)
135
© 2018 by Innovation In Software Corporation
FUNCTION POINTERS
package main
136
}
variable is a shadow {
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 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.
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
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
strings.
\f Formfeed
\n Linefeed
\r Carriage return
\t Tab
\v Vertical tab
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"
)
func main() {
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
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
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() {
156
© 2018 by Innovation In Software Corporation
STRCONV PACKAGE
Operation Description
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
159
© 2018 by Innovation In Software Corporation
FORMAT COMMANDS
Operation Description
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
161
© 2018 by Innovation In Software Corporation
“Develop a passion for learning.”
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 };
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;
benefits including.
class Salaried : public IEmployee {
• Lazy evaluation };
};
• Interface driven . . . . .
int main() {
Person Fred;
implemented in Go Language.
return 0;
169
}
170
© 2018 by Innovation In Software Corporation
CUSTOM TYPES - 2
package main
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"
}
declare a method for the custom type (2)
func (s MyStruct) Add() int {
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() {
173
fmt.Println(c.Multiply())
}
© 2018 by Innovation In Software Corporation
POP QUIZ: WHAT IS THE RESULT?
package main
import "fmt"
func main() {
10 MINUTES
174
© 2018 by Innovation In Software Corporation
POINTER TO RECEIVER
Unless otherwise stipulated, package main
175
© 2018 by Innovation In Software Corporation
EMBEDDING
package main
import "fmt"
street string
city string
Address
"AZ"}}
fmt.Println(c.street, c.city,
c.state)
176
}
EMBEDDING - 2
import "fmt"
street string
city string
state string
Address
surrounding custom type. }
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"
type.
}
func main() {
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()
} }
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
}
}
func (Martian) walk() {
fmt.Println("walking")
type Human struct {
}
}
func (Martian) eat() {
type Martian struct { fmt.Println("eating Humans")
} }
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
191
© 2018 by Innovation In Software Corporation
DEBUG - DUCK TYPING EXAMPLE
func (Human) walk() {
fmt.Println("walking")
package main
}
}
func (Martian) walk() {
fmt.Println("walking")
type Human struct {
}
}
func (Martian) eat() {
type Martian struct { fmt.Println("eating Humans")
} }
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
196
© 2018 by Innovation In Software Corporation
WALKTHROUGH – MARTIAN EATS
197
© 2018 by Innovation In Software Corporation
WALKTHROUGH – THREADS / VARIABLES
198
© 2018 by Innovation In Software Corporation
WALKTHROUGH – THREADS
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
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
permissions is essential for 0644 Read and write for the owner;
everyone else is read
proper application security. 0666 Read and write for everybody
204
owner; read for the file group
"log"
The syntax for the function is: )
func WriteFile(filename string, data
[]byte, perm os.FileMode) error func main() {
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)
)
206
© 2018 by Innovation In Software Corporation
READ FILE
package main
import (
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
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
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
213
© 2018 by Innovation In Software Corporation
package main
214
}
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
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