These are the slides for the seminar to have a basic overview on the GO Language, By Alessandro Sanino.
They were used on a Lesson in University of Turin (Computer Science Department) 11-06-2018
1. THE GO PROGRAMMING LANGUAGE
FROM BEGINNERS TO GOPHERS
ALESSANDRO SANINO
UNIVERSITY OF TURIN
COMPUTER SCIENCE DEPARTMENT
2. AGENDA
Introduction
A bit of context
Go tour
Go VS everybody
Installing Go
Testing and Benchmarking
Coding examples
Conclusions and Q&A
4. LANGUAGE HISTORY
The language was announced in November 2009
First official release in March 2012 (v. 1.0.0)
Inherit characteristics from procedural languages
Supporting new paradigms
Backward C code compatibility
Optimization for concurrency and network efficiency
5. IDEAS
No more boilerplate (ex not as Angular / React / Laravel / etc…)
Easy and efficient concurrency handling (not like js)
Amazing speed (up to 10x faster than node programs which runs the same
algorithm)
Fast to compile (not like npm or composer scripts)
► Slow Reflection Mechanism (improving)
► Huge executable file (result of compilation > 1 MB quite often)
7. GO RULES-OF-THUMB
► Semantic syntax
► Multi-Paradigm, Functional/Procedural Hybrid Style
► Static Types
► Easy access to packages, along with source code (go get)
► Type inference before compiling
► Reflection (basic)
► First letter Uppercase = Public, otherwise Private to the package it belongs to
► static and dynamic alloc, similarly to C language (* and &)
► Attach functions to structs (methods) and implement interfaces transparently
11. ARRAY AND SLICE TYPES
The array type represents a fixed-size array implementation
it is created as
arr := [N]int { /* inline definition */ } //or
var arr2 [N]int
arr2[index] = 5
The array type cannot change its length, if this is necessary slices comes into play.
The slice type represents a dinamic size array implementation
It is created as
slc := arr[1:4] //from arrays or other slices
//via dinamic alloc
slc2 := make([]int, allocatedCells, capacity)
12. ADDITIONAL NOTES
len(arrayOrSliceOrMap) gives the length of the given array or slice or map
Arrays, Slices and Map can be iterated with a for loop
To add elements to slices, use append(slice, items…)
It does not work with arrays!!!
14. MAP AND INTERFACE TYPES
The map type represents a dictionary data structure implementation
it is created as
myMap := make(map[keyType]valueType, capacity)
The interface{} type is a generic type (similar to the object type in C# or the
void* type in C)
16. THE ERROR INTERFACE
A simple string abstraction in its simplest form (stringError)
Error is an interface, so it can be implemented
17. PANIC AND RECOVER
Handles errors the similar way to the try-throw-catch mechanism of other
languages
18. NEVER PANIC UNLESS NECESSARY
► panic is unsafe
► error is better
► few exceptions
19. DEFER
Followed by a function call, tells the runtime to execute it only at the end of
the lifecycle of the caller function (used to close files, connections, recover)
20. GO
By using
go «functionCall»
we are able to create a goroutine which will execute concurrently the specified
function call.
An example of usage is:
go func() {
// do something concurrently
}()
// or
func DoSomethingElse() { fmt.Println(os.args) }
go DoSomethingElse() // does something else concurrently
22. CHANNELS
Used for communication between goroutines
Support atomic insertion and extraction
Can be blocking or non blocking
DO NOT COMMUNICATE BY SHARING MEMORY, INSTEAD
SHARE MEMORY BY COMMUNICATING
24. GOLANG DOCS
godoc tool creates documentation from intestation comments in packages and
functions
https://golang.org website contains all info regarding all non discussed
details (ex. Packages, Channels, Goroutines)
https://godoc.org website contains all useful info regarding standard libraries
(documentation + examples + how-to-document)
26. MODERN ALTERNATIVES TO GO
Node.js
PHP (from version 7)
Python3
Ruby
Java
.NET
etc…
27. GO PERFORMANCE EXAMPLE
Task :
execute 2000 parallel ops
in a web server calling
an endpoint
Result shown:
average response time
N :
number of request considered
to calculate avg time
Source:
https://goo.gl/NarBMV
28. GO VS NODE
Go is a lot faster than nodejs, expecially on concurrent and scalable
applications (nodejs is single threaded, Go can handle millions of concurrent
goroutines on different threads)
29. GO VS NODE (CONTINUES…)
Go is still a niche language and lacks of a lot of tools javascript has to debug,
handle errors, etc…
Nodejs code is harder to maintain, due to the nature of the language
(callback hell, promise hell, etc…)
31. WINDOWS
Download the executable from golang.org website
Install it
The engine will be available in C:/Go
32. LINUX (Ubuntu based)
Follow this guide https://github.com/golang/go/wiki/Ubuntu
Alternatively, run this and setup environment variables (see next slide)
Download tar.gz from golang.org for your distro, then
tar –C /usr/local –xzf go$VERSION.$OS-$ARCH.tar.gz
For example
tar –C /usr/local –xzf go1.2.1.linux-amd64.tar.gz
Add your go tools to your $PATH variable
export PATH=$PATH:/usr/local/go/bin
Verify other GOENV variables are properly set (next slide)
33. GO ENVIRONMENT VARIABLES
GOROOT : The root directory where go engine is installed (/usr/local/go)
GOPATH : The root of your workspace (Go needs it, go files outside won’t be
compiled, go get puts packages in there too)
$HOME/go on Linux
or
%USERPROFILE%/go on windows
GOBIN : The root of the folder containing Go binaries (/usr/local/go/bin)
GOOS and GOARCH : Respectively the OS and the ARCH the go compiler will
compile for
35. go test
Simple integrated tool to test .go files
By following simple rules it is easy to create tests
Tests can also be served as examples and be included in documentation
36. go test
go test (simple as that)
func TestOtherFunction(t *testing.T) tests OtherFunction behaviour
func ExampleOtherFunction() creates a testable example for the function,
which will be included in docs if passes
testing.T contains everything needed to signal pass or errors in tests
Create a file with same name of your .go file and add _test to both filename
and package name to have a test file
37. Test Example
package math
type Int struct {
Val int
}
func (a *Int) Sum(b Int) Int {
return Int{
Val : a.Val + b.Val
}
}
package math_test
import (
"fmt",
"testing",
"math"
)
func TestSum(t *testing.T) {
a := math.int{val : 1}
b := math.int{val : 2}
if a.Sum(b).val != 3 {
t.Error("Something wrong here")
}
}
39. go benchmarks (go test -bench .)
Similarly to Tests we can create benchmarks of our algorithms
func BenchmarkOtherFunction(b *testing.B) benchmarks another function
b.N represents the number of times the benchmark will be run (it depends on
CPU load and speed of the execution)
Benchmarks, like tests, can be aborted at any time
Benchmarks can be done also to verify efficiency of concurrent goroutines
40. go benchmarks (go test -bench .)
package sorting_test
import(
"sorting"
"testing"
)
func BenchmarkSelectionSort(b *testing.B) {
array := initializeBenchIntArray()
for n := 0; n < b.N; n++ {
sorted := sorting.SelectionSort(array)
if !sorting.isSorted(sorted) {
b.Error("Not sorted")
}
}
}
43. fibonacci.go
Create a program that prints the Fibonacci sequence up to a certain N we pass as
parameter
$> ./fibo 5
$> 0 1 1 2 3
$> ./fibo
$> missing N
$> ./fibo -1
$> error
$> ./fibo invalid
$> error
45. Producer - Consumer Problem in GO
Create a simulation of the Producer - Consumer Problem in GO
$> ./prodCons
$> Produced item 81 by Producer 0
$> Produced item 887 by Producer 1
$> Consumed item 81 by Consumer 1
$> Produced item 847 by Producer 0
$> Produced item 59 by Producer 1
$> ….
47. Writing an API in Go
There are a lot of useful usable framework, and they vary in efficiency and
readibility
labstack/echo is the minimal engine, with a speed up to 10 times faster than
net/http package
goadesign/goa is a more complex engine, design oriented, to develop
complex API
Today we will use labstack/echo !!!
48. Writing an API in Go
Create an api to get quotes and show them to users
$> ./server &
$> ./client gimmeRandomQuote
$> One apple per day keeps the doctor away
49. Writing an API in Go
We need:
Golang server (labstack/echo) to handle the backend
Golang Client to send requests to the server as
frontend
52. We learnt to
Write go code following examples and guidelines
Test code and benchmark performance
Write an API to serve content to customers
53. REFERENCES
GO by example: https://gobyexample.com
Go comparison with other languages (Toptal) : https://goo.gl/NarBMV
Go website : https://golang.org
Godoc website : https://godoc.org
Godoc guidelines : https://goo.gl/iG5X28
Go books : https://goo.gl/hXfZyC