SlideShare a Scribd company logo
1 of 55
THE GO PROGRAMMING LANGUAGE
FROM BEGINNERS TO GOPHERS
ALESSANDRO SANINO
UNIVERSITY OF TURIN
COMPUTER SCIENCE DEPARTMENT
AGENDA
 Introduction
 A bit of context
 Go tour
 Go VS everybody
 Installing Go
 Testing and Benchmarking
 Coding examples
 Conclusions and Q&A
A BIT OF
CONTEXT
GOLANG HISTORY AND USAGE MACROAREAS
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
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)
GO TOUR
LANGUAGE SYNTAX AND FEATURES
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
SEMANTIC SYNTAX
ASSIGNING VALUES
NATIVE TYPES
 int (int8 int16 int32 int64 uint8 uint16 uint32 uint64)
 float (float32)
 double (float64)
 string
 map[type1]type2 (ex. map[string]int)
 interface{}
 slice types and array types (ex int[], float32[])
 Error interface (error)
 Structs (struct)
 Generic Interfaces (interface)
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)
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!!!
ADDITIONAL NOTES
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)
MISCELLANEOUS EXAMPLES
THE ERROR INTERFACE
 A simple string abstraction in its simplest form (stringError)
 Error is an interface, so it can be implemented
PANIC AND RECOVER
 Handles errors the similar way to the try-throw-catch mechanism of other
languages
NEVER PANIC UNLESS NECESSARY
► panic is unsafe
► error is better
► few exceptions
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)
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
GO
Goroutines are one of the cases where PANIC - RECOVER is useful
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
CHANNEL EXAMPLE
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)
GO VS EVERYBODY
COMPARISON BETWEEN GO AND OTHER TECHNOLOGIES
MODERN ALTERNATIVES TO GO
 Node.js
 PHP (from version 7)
 Python3
 Ruby
 Java
 .NET
 etc…
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
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)
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…)
INSTALLING GO
HOW TO INSTALL GO TOOLS ON YOUR PC
WINDOWS
 Download the executable from golang.org website
 Install it
 The engine will be available in C:/Go
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)
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
TESTING AND BENCHMARKING
USING GO TOOLS FOR EASY TESTS AND BENCHMARKS
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
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
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")
}
}
Testable Example (stringutil_test.go)
package stringutil_test
import (
"fmt"
)
func ExampleReverse() {
fmt.Println(stringutil.Reverse("hello")
// Output: olleh
}
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
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")
}
}
}
BREAK TIME
HANDS DIRTY IN CODE
SOME GUIDED GO EXERCISES
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
WORK TIME
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
$> ….
WORK TIME
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 !!!
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
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
WORK TIME
CONCLUSIONS
WHAT DO WE LEARNT SO FAR
We learnt to
 Write go code following examples and guidelines
 Test code and benchmark performance
 Write an API to serve content to customers
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
ABOUT THE AUTHOR
https://linkedin.com/in/alessandrosanino
https://github.com/saniales
https://github.com/thebotguys
https://github.com/crypto-crew-tech
Alessandro Sanino
Bandito – Bra (CN), Italy
Currently Blockchain Researcher @ unito
“
”
Go is not meant to innovate
programming theory.
It’s meant to innovate
programming practice
~ Samuel Tesla, Article Writer and Programmer

More Related Content

What's hot

Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go languageTzar Umang
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming languageSlawomir Dorzak
 
Ekon bestof rtl_delphi
Ekon bestof rtl_delphiEkon bestof rtl_delphi
Ekon bestof rtl_delphiMax Kleiner
 
EuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangEuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangMax Tepkeev
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of GoFrank Müller
 
Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Max Kleiner
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about goDvir Volk
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Sylvain Wallez
 
Command Line Arguments with Getopt::Long
Command Line Arguments with Getopt::LongCommand Line Arguments with Getopt::Long
Command Line Arguments with Getopt::LongIan Kluft
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with pythonroskakori
 
Turbo basic commands
Turbo basic commandsTurbo basic commands
Turbo basic commandsjulviapretty
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 

What's hot (20)

Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go language
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
 
FTD JVM Internals
FTD JVM InternalsFTD JVM Internals
FTD JVM Internals
 
Introduction to Go programming language
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
 
Golang
GolangGolang
Golang
 
Ekon bestof rtl_delphi
Ekon bestof rtl_delphiEkon bestof rtl_delphi
Ekon bestof rtl_delphi
 
Vim and Python
Vim and PythonVim and Python
Vim and Python
 
EuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To GolangEuroPython 2016 - Do I Need To Switch To Golang
EuroPython 2016 - Do I Need To Switch To Golang
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2Pascal script maxbox_ekon_14_2
Pascal script maxbox_ekon_14_2
 
10 reasons to be excited about go
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
 
Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!Inside the JVM - Follow the white rabbit!
Inside the JVM - Follow the white rabbit!
 
Unit VI
Unit VI Unit VI
Unit VI
 
Command Line Arguments with Getopt::Long
Command Line Arguments with Getopt::LongCommand Line Arguments with Getopt::Long
Command Line Arguments with Getopt::Long
 
Open source projects with python
Open source projects with pythonOpen source projects with python
Open source projects with python
 
Perl Modules
Perl ModulesPerl Modules
Perl Modules
 
Turbo basic commands
Turbo basic commandsTurbo basic commands
Turbo basic commands
 
I phone 12
I phone 12I phone 12
I phone 12
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
Mysql
MysqlMysql
Mysql
 

Similar to The GO Language : From Beginners to Gophers

Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoRodolfo Carvalho
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Robert Stern
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golangYoni Davidson
 
Easy deployment & management of cloud apps
Easy deployment & management of cloud appsEasy deployment & management of cloud apps
Easy deployment & management of cloud appsDavid Cunningham
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_netNico Ludwig
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using SwiftDiego Freniche Brito
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMRaveen Perera
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Hermann Hueck
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005Tugdual Grall
 
Debugging Python with gdb
Debugging Python with gdbDebugging Python with gdb
Debugging Python with gdbRoman Podoliaka
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes
 
"Modern DevOps & Real Life Applications. 3.0.0-devops+20230318", Igor Fesenko
"Modern DevOps & Real Life Applications. 3.0.0-devops+20230318", Igor Fesenko "Modern DevOps & Real Life Applications. 3.0.0-devops+20230318", Igor Fesenko
"Modern DevOps & Real Life Applications. 3.0.0-devops+20230318", Igor Fesenko Fwdays
 
The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202Mahmoud Samir Fayed
 
Aspect-oriented programming in Perl
Aspect-oriented programming in PerlAspect-oriented programming in Perl
Aspect-oriented programming in Perlmegakott
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Guillaume Laforge
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packagesAjay Ohri
 
The Ring programming language version 1.7 book - Part 92 of 196
The Ring programming language version 1.7 book - Part 92 of 196The Ring programming language version 1.7 book - Part 92 of 196
The Ring programming language version 1.7 book - Part 92 of 196Mahmoud Samir Fayed
 

Similar to The GO Language : From Beginners to Gophers (20)

Go 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX Go
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 
Golang workshop
Golang workshopGolang workshop
Golang workshop
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golang
 
Easy deployment & management of cloud apps
Easy deployment & management of cloud appsEasy deployment & management of cloud apps
Easy deployment & management of cloud apps
 
(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net(1) c sharp introduction_basics_dot_net
(1) c sharp introduction_basics_dot_net
 
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides:  Let's build macOS CLI Utilities using SwiftMobileConf 2021 Slides:  Let's build macOS CLI Utilities using Swift
MobileConf 2021 Slides: Let's build macOS CLI Utilities using Swift
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBM
 
Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)Composing an App with Free Monads (using Cats)
Composing an App with Free Monads (using Cats)
 
Introduction To Groovy 2005
Introduction To Groovy 2005Introduction To Groovy 2005
Introduction To Groovy 2005
 
Debugging Python with gdb
Debugging Python with gdbDebugging Python with gdb
Debugging Python with gdb
 
Geeks Anonymes - Le langage Go
Geeks Anonymes - Le langage GoGeeks Anonymes - Le langage Go
Geeks Anonymes - Le langage Go
 
"Modern DevOps & Real Life Applications. 3.0.0-devops+20230318", Igor Fesenko
"Modern DevOps & Real Life Applications. 3.0.0-devops+20230318", Igor Fesenko "Modern DevOps & Real Life Applications. 3.0.0-devops+20230318", Igor Fesenko
"Modern DevOps & Real Life Applications. 3.0.0-devops+20230318", Igor Fesenko
 
The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202The Ring programming language version 1.8 book - Part 95 of 202
The Ring programming language version 1.8 book - Part 95 of 202
 
Aspect-oriented programming in Perl
Aspect-oriented programming in PerlAspect-oriented programming in Perl
Aspect-oriented programming in Perl
 
Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007Groovy Update - JavaPolis 2007
Groovy Update - JavaPolis 2007
 
r,rstats,r language,r packages
r,rstats,r language,r packagesr,rstats,r language,r packages
r,rstats,r language,r packages
 
The Ring programming language version 1.7 book - Part 92 of 196
The Ring programming language version 1.7 book - Part 92 of 196The Ring programming language version 1.7 book - Part 92 of 196
The Ring programming language version 1.7 book - Part 92 of 196
 
Introduction to Apache Beam
Introduction to Apache BeamIntroduction to Apache Beam
Introduction to Apache Beam
 

Recently uploaded

What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....kzayra69
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfLivetecs LLC
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfIdiosysTechnologies1
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作qr0udbr0
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...Technogeeks
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfStefano Stabellini
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)jennyeacort
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfFerryKemperman
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentationvaddepallysandeep122
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 

Recently uploaded (20)

What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....What are the key points to focus on before starting to learn ETL Development....
What are the key points to focus on before starting to learn ETL Development....
 
How to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdfHow to Track Employee Performance A Comprehensive Guide.pdf
How to Track Employee Performance A Comprehensive Guide.pdf
 
Best Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdfBest Web Development Agency- Idiosys USA.pdf
Best Web Development Agency- Idiosys USA.pdf
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作英国UN学位证,北安普顿大学毕业证书1:1制作
英国UN学位证,北安普顿大学毕业证书1:1制作
 
What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...What is Advanced Excel and what are some best practices for designing and cre...
What is Advanced Excel and what are some best practices for designing and cre...
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
 
Xen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdfXen Safety Embedded OSS Summit April 2024 v4.pdf
Xen Safety Embedded OSS Summit April 2024 v4.pdf
 
How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
Call Us🔝>༒+91-9711147426⇛Call In girls karol bagh (Delhi)
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
Introduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdfIntroduction Computer Science - Software Design.pdf
Introduction Computer Science - Software Design.pdf
 
PREDICTING RIVER WATER QUALITY ppt presentation
PREDICTING  RIVER  WATER QUALITY  ppt presentationPREDICTING  RIVER  WATER QUALITY  ppt presentation
PREDICTING RIVER WATER QUALITY ppt presentation
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 

The GO Language : From Beginners to Gophers

  • 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
  • 3. A BIT OF CONTEXT GOLANG HISTORY AND USAGE MACROAREAS
  • 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)
  • 6. GO TOUR LANGUAGE SYNTAX AND FEATURES
  • 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
  • 10. NATIVE TYPES  int (int8 int16 int32 int64 uint8 uint16 uint32 uint64)  float (float32)  double (float64)  string  map[type1]type2 (ex. map[string]int)  interface{}  slice types and array types (ex int[], float32[])  Error interface (error)  Structs (struct)  Generic Interfaces (interface)
  • 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
  • 21. GO Goroutines are one of the cases where PANIC - RECOVER is useful
  • 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)
  • 25. GO VS EVERYBODY COMPARISON BETWEEN GO AND OTHER TECHNOLOGIES
  • 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…)
  • 30. INSTALLING GO HOW TO INSTALL GO TOOLS ON YOUR PC
  • 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
  • 34. TESTING AND BENCHMARKING USING GO TOOLS FOR EASY TESTS AND BENCHMARKS
  • 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") } }
  • 38. Testable Example (stringutil_test.go) package stringutil_test import ( "fmt" ) func ExampleReverse() { fmt.Println(stringutil.Reverse("hello") // Output: olleh }
  • 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") } } }
  • 42. HANDS DIRTY IN CODE SOME GUIDED GO EXERCISES
  • 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
  • 51. CONCLUSIONS WHAT DO WE LEARNT SO FAR
  • 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
  • 55. “ ” Go is not meant to innovate programming theory. It’s meant to innovate programming practice ~ Samuel Tesla, Article Writer and Programmer

Editor's Notes

  1. 5 minutes available for questionsb
  2. Theory good, practice better when biz