CS 370
–
Summer 2019
Introduction
to Go
Programming
Language
Presenting by Group 1
Presentation Overview
GO
KEY TOPICS
What is Go programming language?
History of Go
Why go is born?
Designer team and users
Some outstanding features
Some basic syntax
May be demo here
GO programming language
What is GO programming language?
03
• open source
• concurrent
• garbage-collected
• efficient
Go, also known as Golang,is a statically
typed, compiled programming language
designed at Google. Go is a procedural
programming language.
• scalable
• simple
• fun
• boring (to some)
A young programming
language
HISTORY OF
GOLANG
LATE 2007: BORN
It was developed in 2007 by Robert
Griesemer, Rob Pike, and Ken Thompson
at Google
2009:OPEN SOURCE
It became open source in November 2009
TODAY:MORE POPULAR
More and more developers use it
Today's version is 1.12.9
Design team
Robert Griesemer
V8 JavaScript engine, Java
HotSpot VM
Fathers Of GOLANG
Rob Pike
UNIX, Plan 9, UTF-8
Ken Thompson
UNIX, Plan 9, B language,
UTF-8
Why GO?
• C++ for servers, plus lots of Java and
Python
• Thousand of engineers
• Gazillions of lines of code
• Distributed build system
• Zillions of machines, which are treated as a
modest number of compute clusters
GO programming language
Go is an answer to
problems of scale
at Google
GO’s Goals
GO
Go was designed by and for people who write –and read and
debug and maintain –large software systems.
GO programming language
1
2
3
Go’s purpose is not research programming language design.
Go’s purpose is to make its designers’ programming lives better.
Who is the
User?
Google
Youtube
Docker
SoundCloud
Advantages of GOLANG
GO grows faster than any other language. 1
5
2
3
4
GO compiled into many platforms.
GO uses multiple cores.
GO has Concurrency and Goroutines.
Easy to maintain.
Polularity and potential future
03
In early 2017, according to Zdnet's statistics,
GO surpassed its competitors, the popularity
was 2.6%, climbing from the 54th position in
2016 to the 13th position. GO is the only
language with such rapid growth.
GO grows faster than any other
language
Fast build and multiple flatforms03
The Go programming language is also compiled like Java,
but unlike Java, it requires Java Virtual Machine to execute
because Java compiles into Byte code, Go compiles to
Machine code so it can run immediately with the operating
system. It compiles without any further installation. That
means, from my computer, I can compile programs running
on Mac, Window, Linux.
GO compiled into many platforms
Multiple cores and easily to scale up 03
In the 1990s, one of the major changes in computer hardware
was the addition of cores. Quad-core and octa-core CPUs
significantly improve performance. However, programming
languages created before that time only run on single-core
computers, and they are built not intended to run on multi-
core. But Go is different, the late born has created an
advantage for it, computer hardware can expand the core,
making Go a language that can be more easily scaled.
GO uses multiple cores
Frendly with HEAP and memory 03
Concurrency is a key feature of the Go programming
language to utilize CPU processing power. Usually other
programming languages must depend on the allocation of
operating system resources to run Concurrency, while Go
can run Concurrency without operating system dependency.
Concurrency is similar to thread, in Go, communication
between goroutine is quite simple with channel, can transmit
data between goroutine together by any kind of data.
GO has Concurrency and Goroutines
Heap
JAVA
If a Java Thread is created, it uses
approximately 1MB of Heap memory, if
you create 1000 Thread like that, they
will create a heap pressure that will
cause the system to be turned off
because of a memory shortage. On
the other hand, it is difficult to
communicate between two or more
Thread.
GOLANG
But with GO is different, when using
multi-core processors is feasible,
Goroutines can completely replace
Thread. Each goroutines only uses
2KB of memory from the heap, so you
can create millions of goroutines at
any time.
More about Goroutine
Goroutine
Code Example
packagemain
import"fmt"
funcf(from string){
fori :=0;i <3;i++{
fmt.Println(from,":",i)
}
}
funcmain(){
f("direct")
// Using go f() to execute function f() in
goroutines.
gof("goroutine")
gofunc(msg string){
fmt.Println(msg)
}("going")
fmt.Scanln()
fmt.Println("done")
}
// Output
direct :0
direct :1
direct :2
goroutine :0
going
goroutine :1
goroutine :2
<enter>
Done
Advantages of Goroutine
Goroutines use memory flexibly for
segmented stack, which will increase
memory when needed.
The boot time of Goroutines is faster than
Thread.
Communicate between Goroutines using
channel is extremely safe.
Goroutines and OS threads do not exist 1:
1. Each Gorountine can run multiple threads
at the same time, they can be combined into
OS threads.
GO programming language
Maximize simplification
03
GO's syntax is extremely simple, without too
complicated syntax like other languages. Go
developers come from Google, a large-scale code-
base place, and thousands of developers work
together, so source code must be simple for any
developer to understand and each block of code will
minimize side effects. That makes the code easily to
be maintained an changed.
Easy to maintain
Why we can
say GO is
Special?
Go ignores many features of OOP
(Object-oriented programming)
•No Class. Everything is bundled into
packages. Go only have structs.
•No inheritance support.
•No constructor, annotation, generics or
exceptions.
That makes Go different from the
rest. Looking at the positive side,
it makes the code more concise
and easier to understand.
GO programming language
Things that are supported by GO
Some old things, some new things
Overvie
w
-All programs written from Go are
created by main packages and
packages used to run is main
-To use other packages, we have to
import, for example if we want to
print a text to the console, we must
use the fmtpackage
Code
Packages
packagemain
import"fmt"
funcmain(){
fmt.Println("Hello World")
}
GO programming language
Code
Over view
-Go's syntax is similar to C but there
are many other points, for example,
there is no semicolon at the end of the
statement or the data type declared
after the variable name
-When performing calculations
between variables with different data
types, we need type conversion:
Formula T (v) where Tis the data type
and vis the value
-Constant declaration is similar to
declaring a variable but using const and
not using the abbreviated syntax “:=“
Variables
varmessage string
varc,python,java bool
vari,j int=1,2
k :=3
i :=55// int
j :=67.8// float 64
sum :=i +int(j)// type conversion
fmt.Println(sum)// output: 122
constPi =3.14
GO programming language
Overvie
w
-Declare the function using the
keyword func, notice that the input
parameter also declares the data type
after the parameter name
-A special feature in GO is that the
function can return many results
Code
Functions
funcadd(x int,y int)int{
returnx +y
}
// funtion that return 2 values
funcswap(x,y string)(string,
string){
returny,x
}
GO programming language
Code
Over view
-In GO, only 1 type of loop is used: for
loop. Usage is similar to other
languages but the declaration of
variables, repeating conditions, ... does
not need to be enclosed in round
brackets
-forloop only using a repeating
condition, it acts like a whilein other
languages
Loop
sum :=0
fori :=0;i <10;i++{
sum +=i
}
fmt.Println(sum)
sum :=0
forsum <10{
sum +=sum
}
fmt.Println(sum)
GO programming language
Overvie
w
-Conditional statement in GO use if,
else, switch, and like forloop we also
do not need round brackets
-With the ifstatement, we can
declare the variable in the conditional
statement, and this variable will only
work in the block of the ifor else
statement
Code
if andelse
import(
"fmt"
"math"
)
funcpow(x,n,limit float64)
float64{
ifv :=math.Pow(x,n);v <limit {
returnv
}else{
fmt.Printf("%g>= %g\n",v,limit)
}
returnlimmit
}
GO programming language
Code
Over view
-The expression in the switch cannot
use a constant. There is no need for
break commands in each case.
Therefore only the first satisfied case is
run (from top to bottom)
-You can use multiple conditions in a
case, or use the keyword fallthroughto
allow the next command continue
Switchcase
switchnum :=10;{
casenum <50:
fmt.Printf("%d< 50\n",num)//
print: 10 < 50
casenum <100:
fmt.Printf("%d< 100\n",num)//
will not be executed
default:
fmt.Printf("I don't know",num)
}
GO programming language
num :=10;
switch{
casenum >=0&&num <=50:
fmt.Printf("%d< 50 \n",num)// print: 10 < 50
fallthrough
casenum <100:
fmt.Printf("%d< 100 \n",num)//print: 10 < 100
default:
fmt.Printf("I don't know",num)
}
Overvie
w
-Delay (defer) is a fairly new concept
in flow control. It allows a command
to be called but does not execute
immediately and delays until the
surrounding commands return results
-The commands that are called via
the defer keyword will be put on a
stack, work following last-in-first-out
mechanism
Code
defer
packagemain
import"fmt"
funcmain(){
deferfmt.Println("World")// Delay
print: "World"
fmt.Println("Hello")// Print:
"Hello"
// output : Hello World
}
GO programming language
Overview
-Slice is a reference to Array, it describes part (or all) Array. It has dynamic size so it
is often used more than Array.
-Slice can be created from an Array by providing 2 indexes (low and high) to locate
the element in Array.
-A slice will have two attributes: length and capacity. Length is the number of elements
in Slice, capacity is the number of elements in Array that the Slice refers to (starting
from the first element of Slice). To get the length we use len(), to get the capacity, we
use cap()
-Because slices are only references to Array, changing the value of slices will change
the value of the Array. If there are multiple slices that reference an Array, changing the
value of a slice can change the value of other slices.
Slices
GO programming language
Code for
Slices
GO programming language
s :=[]int{2,3,5,7,11,13}
s =s[0:0]// s = [], len(s) = 0, cap(s) = 6
s =s[0:4]// s = [2, 3, 5, 7], len(s) = 4, cap(s) = 6
s =s[2:4]// s = [5, 7], len(s) = 2, cap(s) = 4
Over view
-Array in GO is similar to other
languages, but it has fixed size and all
elements must be of the same data type
-Unlike most other languages, Array in
GO is not a reference type but a value
type. When assigning its value to a new
variable, it will create a copy of the old
Array, and any changes to the new
Array will not affect the old Array
Structs
packagemain
import(
"fmt"
)
typeStudentstruct{
name string
age int
}
funcmain(){
s1 :=Student{"Steve",30}
s2 :=Student{"Steve",30}
s3 :=Student{"Job",30}
ifs1 ==s2 {
fmt.Println("s1 = s2")
}else{
fmt.Println("s1 != s2")
}
}
GO programming language
Code
Overview
-Map is a set of elements stored as key -value. The key in the map has a comparable and
non-duplicate data type. To create a map, use the make() function with the following
formula:
make(map[type of key]type of value)
-To delete the element in the map, we use the delete() function and provide the key of the
element to be deleted.
-To access the element in the map, we call the map with the key of the element. If that
key does not exist, we will get the value zero value (depending on the data type).
The first value is the same as the above example, the second value will be true if the
element is in map and false if the element does not exist.
Maps
GO programming language
Code for
Maps
GO programming language
vardemoMap map[string]int
ifdemoMap ==nil{
fmt.Println("Map has nil value.")
demoMap =make(map[string]int)
}
languages :=make(map[string]float32)
languages["go"]=0.63
languages["java"]=1.03
delete(languages,"go")
m :=make(map[string]int)
m["Answer"]=42
delete(m,"Answer")
fmt.Println(m["Answer"])
v,ok :=m["Answer"]
fmt.Println("Value of element: ",v)// v= 0
fmt.Println("Exist or not ",ok)// ok = false
Over view
We can use struct instead of class.
However, struct only has properties and
no methods. To apply the method as
other object-oriented languages, we will
need to declare the function with a
special parameter called the receiver
argument. The receiver argument is in
the middle of the func keyword and the
function name, it will indicate a type
(usually a struct) to apply this function
as a method.
Structs
packagemain
import(
"fmt"
"math"
)
typeVertexstruct{
X,Y float64
}
// Creat method abs() for struct
Vertex(receiver argument)
func(v Vertex)Abs()float64{
returnmath.Sqrt(v.X*v.X +v.Y*v.Y)
}
funcmain(){
v :=Vertex{3,4}
fmt.Println(v.Abs())
}
GO programming language
Code
Overview
-Interface is a definition of method sets that an object needs to comply with (similar to
other object-oriented languages). When a type contains methods as declared in the
interface, it is deploying that interface.
-The interface implementation type must have a full set of methods defined in the
interface.
-An interface without any method is called an Emtpy Interface. The empty interface
can store all types of data, so it is often used in the case of processing functions that
need dynamic parameters (all data types).
Interfaces
GO programming language
Code for
Interfaces
GO programming language
packagemain
import"fmt"
// Interface I has method M()
typeIinterface{
M()
}
typeTstruct{
S string
}
// Define method M() for struct T
func(t T)M(){
fmt.Println(t.S)
}
funcmain(){
// init variable i with type interface I
vari I =T{"hello"}
// call method M()
i.M()
}
Code for
Interfaces
(continue)
GO programming language
packagemain
import"fmt"
typeIinterface{
M(),
N()
}
typeTstruct{
S string
}
func(t T)M(){
fmt.Println(t.S)
}
funcmain(){
vari I =T{"hello"}
i.M()
// The result will be an error because of struct T
implement interface I,but there are not enough declared
methods (missing method N ())
}
Code for
Interfaces
(continue)
GO programming language
packagemain
import"fmt"
funcmain(){
vari interface{}// Empty interface
i =42
describe(i)
i ="hello"
describe(i)
}
// we can pass all data type in to function describe
funcdescribe(i interface{}){
fmt.Printf("(%v, %T)\n",i,i)
}