SlideShare a Scribd company logo
1 of 42
Download to read offline
Geek Anonyme - 23/09/2020
Thomas Hayen - Gabismartcare
Agenda
- Introduction
- Why and What is Go?
- Small tour
INTRODUCTION
Who am I?
- Thomas Hayen
- Computer engineer ULg 2010
- Java developer since 2010
- Go developer since 2019
Java?
Back to 2019…
Goals:
- Event sourced architecture
- Cloud based (Docker, Kubernetes,...)
- Micro services
- database(s)
- Messaging system
Java?
First version
- 6 microservices just running (no clients)
- > 1Gb memory RAM
- CPU usage >5%
- Images docker +/- 150Mo /container
- Starting time +/- 2 sec container (5 sec if docker is not spawned)
Let’s try Go
- 6 microservices just running (no clients)
- < 20 Mb memory RAM
- CPU usage < 1%
- Images docker +/- 5Mo /container
- Starting time < 1 sec container (2 sec if docker is not spawned)
$ docker images
geek/go-hello latest 760ba5405773 4.78MB
geek/spring-hello latest a224fb9bc642 121MB
$ docker stats
CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM %
e680f347aee5 JAVA 0.09% 200.6MiB / 23.12GiB 0.85%
3061e909e394 GO 0.00% 1.812MiB / 23.12GiB 0.01%
Docker image comparison
WHY Go AND WHAT IS Go?
Why Go?
- Complexity required to use languages
- Processors are multi-core, most languages offered little help to program them efficiently and safely.
- Frustration with existing languages: one had to choose either efficient compilation, efficient
execution, or ease of programming
- slow builds
- uncontrolled dependencies
- each programmer using a different subset of the language
- poor program understanding (code hard to read, poorly documented, and so on)
- ...
https://talks.golang.org/2012/splash.article
Go Spec
- C like
- Network (web app, …)
- Multiprocessor
- Scaling (in term of dependency and build)
- Easy to use
What is Go?
- Designed at Google by Robert Griesemer, Rob Pike and Ken Thompson
- Compiled,
- Concurrent,
- Garbage-collected,
- Statically typed language
- Fast build
- Simple
- Great environment
SMALL TOUR
So let’s Go - Hello world...
// create package main every program will be in package main and have a main function
package main
// import keyword is used to import "fmt" in your package
import "fmt"
// func is used to create function entry point
func main() {
hello := "Hello world"
fmt.Println(hello)
}
Sample example
//main.go
package main
func sum(a, b int) int {
return a + b
}
Testing
//main_test.go
package main
import "testing"
func TestSum(t *testing.T) {
if 2 != sum(1,1) {
t.Errorf("Error 1+1 should be 2")
}
}
Testing
func TestMultipleInputOutput(t *testing.T) {
tests := []struct {
name string
input1, input2, expected int
}{
{name: "1+1=2", input1: 1, input2: 1, expected: 2},
{name: "5+5=10", input1: 5, input2: 5, expected: 10},
{name: "-1-0=-1", input1: -1, input2: 0, expected: 3},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
value := sum(tt.input1, tt.input2)
if value != tt.expected {
t.Errorf("%d + %d should be %d, got %d", tt.input1, tt.input2, tt.expected, value)
}
})
}
}
Testing
$ go test -v *
=== RUN TestMultipleInputOutput
=== RUN TestMultipleInputOutput/1+1=2
=== RUN TestMultipleInputOutput/5+5=10
=== RUN TestMultipleInputOutput/-1-0=-1
main_test.go:17: -1 + 0 should be 3, got -1
--- FAIL: TestMultipleInputOutput (0.00s)
--- PASS: TestMultipleInputOutput/1+1=2 (0.00s)
--- PASS: TestMultipleInputOutput/5+5=10 (0.00s)
--- FAIL: TestMultipleInputOutput/-1-0=-1 (0.00s)
FAIL
FAIL command-line-arguments 0.002s
FAIL
A more complete example
package main
import (
"fmt"
random "math/rand"
"time"
)
import "errors"
// Upper first letters are exported
var (
NonExistingError = errors.New("NonExistingError")
NonExistingError2 = errors.New("NonExistingError2")
NonExistingError3 = errors.New("NonExistingError3")
)
// Lower letters not
const (
lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz"
)
A more complete example
func main() {
inputArray, err := generateSliceOfRandomString(10)
checkError(err)
fmt.Println(inputArray)
quicksort(inputArray, 0, len(inputArray)-1)
for i, s := range inputArray {
fmt.Println(fmt.Sprintf("At index %d, found %s", i, s))
}
}
A more complete example
func checkError(err error) {
if err != nil {
switch err {
case NonExistingError:
fmt.Println("This is an NonExistingError")
case NonExistingError2:
fallthrough
case NonExistingError3:
fmt.Println("This is an NonExistingError2 or 3")
default:
panic(err)
}
}
}
A more complete example
func generateSliceOfRandomString(size int) ([]string, error) {
startingTime := time.Now()
defer printDuration(startingTime) // defer
rand.Seed(startingTime.UnixNano())
var slice []string = make([]string, size) // slice
time.Sleep(1 * time.Second)
for i := 0; i < size; i++ {
b := make([]byte, 16)
for i := range b {
b[i] = lowerCaseLetters[random.Intn(len(lowerCaseLetters))] //Renamed in imports
}
slice[i] = string(b)
}
return slice, nil
}
func printDuration(startingTime time.Time) {
fmt.Println("Execution time: ", time.Now().Sub(startingTime))
}
A more complete example
func quicksort(arr []string, start, end int) {
if (end - start) < 1 {
return
}
pivot := arr[end]
splitIndex := start
for i := start; i < end; i++ {
if arr[i] < pivot {
arr[splitIndex], arr[i] = arr[i], arr[splitIndex]
splitIndex++
}
}
arr[end], arr[splitIndex] = arr[splitIndex], pivot
quicksort(arr, start, splitIndex-1)
quicksort(arr, splitIndex+1, end)
}
Output
$ go run main.go
Execution time: 1.000107637s
[uovedvemekymaops xrlzrshegtbdnows enhwynbzqfjpbmpq lhuxkoryozievjiu ecomkhxglzxdjngf kipvolyziwfagacv
knyjxajpcspjgkbc jthfcayshhotvcxj wipxnhtaoqlgtjsk oabiguaudkzryxfn]
At index 0, found ecomkhxglzxdjngf
At index 1, found enhwynbzqfjpbmpq
At index 2, found jthfcayshhotvcxj
At index 3, found kipvolyziwfagacv
At index 4, found knyjxajpcspjgkbc
At index 5, found lhuxkoryozievjiu
At index 6, found oabiguaudkzryxfn
At index 7, found uovedvemekymaops
At index 8, found wipxnhtaoqlgtjsk
At index 9, found xrlzrshegtbdnows
Go concurrency
func main() {
inputArray, _ := generateSlice(100)
wg := sync.WaitGroup{}
fmt.Println(inputArray)
quicksortConcurrent(wg, inputArray, 0, len(inputArray)-1)
wg.Wait()
fmt.Println("Finished")
for i, s := range inputArray {
fmt.Println(fmt.Sprintf("At index %d, found %s", i, s))
}
}
func quicksortConcurrent(wg sync.WaitGroup,arr
[]string,start,end int){
wg.Add(1)
defer wg.Done()
if (end - start) < 1 {
return
}
pivot := arr[end]
splitIndex := start
for i := start; i < end; i++ {
if arr[i] < pivot {
arr[splitIndex], arr[i] = arr[i], arr[splitIndex]
splitIndex++
}
}
arr[end], arr[splitIndex] = arr[splitIndex], pivot
go quicksortConcurrent(wg, arr, start, splitIndex-1)
go quicksortConcurrent(wg, arr, splitIndex+1, end)
}
Benchmark… Yet another Go feature...
package main
import (
"sync"
"testing"
)
var inputArray []string
func init() {
inputArray, _ = generateSlice(500)
}
func BenchmarkFuncNormal(b *testing.B) {
for i := 0; i < b.N; i++ {
quicksort(inputArray, 0, len(inputArray)-1)
}
}
func BenchmarkFuncConcurrent(b *testing.B) {
for i := 0; i < b.N; i++ {
quicksortConcurrent(sync.WaitGroup{}, inputArray, 0, len(inputArray)-1)
}
}
Let’s compare executions
$ go test -bench=.
goos: linux
goarch: amd64
pkg: geek
BenchmarkFuncNormal-4 862 1415186 ns/op
BenchmarkFuncConcurrent-4 10000 484759 ns/op
PASS
ok geek 7.233s
Go Channels
package main
import "fmt"
func sum(s []int, c chan int) {
sum := 0
for _, v := range s {
sum += v
}
c <- sum // send sum to c
}
func main() {
s := []int{7, 2, 8, -9, 4, 0}
c := make(chan int)
go sum(s[:len(s)/2], c)
go sum(s[len(s)/2:], c)
x, y := <-c, <-c // receive from c
fmt.Println(x, y, x+y)
}
$ go run main.go
-5 17 12
Go dependency
go.mod
module geek
go 1.15
require (
cloud.google.com/go/firestore v1.3.0
github.com/lib/pq v1.8.0
)
$ go mod download
$ go get github.com/lib/pq
Is Go an object oriented language?
We can define structure and apply method on it
type Animal struct {
Name string // This is public
surname string // This is “private”
}
func (Animal) Speak() {
fmt.Println("I'm an animal")
}
func main() {
_ = Animal{
Name: "name",
surname: "Surname",
}
a := Animal{"name","surname"} //Work but not recommended
a.Speak()
}
Is Go an object oriented language?
There is also a way to embed types
type Dog struct {
Animal
}
func main() {
dog := Dog{
Animal{
Name: "Name",
Surname: "SurName",
},
}
dog.Name = "dog name"
dog.Speak() //Print I'm an animal
}
Is Go an object oriented language?
We can override method
func (d Dog) Speak() {
fmt.Println(fmt.Sprintf("I'm an dog and my name is %s", d.Name));
}
func main() {
dog := Dog{}
dog.Speak() //Print I'm a dog and my name is
}
Is Go an object oriented language?
But…
func main() {
dog := Dog{}
animals := []Animal{}
animals = append(animals, dog) //Cannot use 'dog' (type Dog) as type Animal
}
Is Go an object oriented language?
Solution
type Speaker interface {
Speak()
}
func main() {
dog := Dog{}
animals := []Speaker{}
animals = append(animals, dog)
for _, animal := range animals {
animal.Speak() //Print I'm an dog and my name is
}
}
Go has pointer
package main
import "fmt"
type Car struct {
Model string
}
func main() {
car := Car{Model: "Audi"}
ptrOnCar := &car
fmt.Println((*ptrOnCar).Model) // Print Audi
fmt.Println(ptrOnCar.Model) // Print Audi
}
Go pass by value
package main
import "fmt"
type Car struct {
Model string
}
func (c Car) SetModel(model string) {
c.Model = model
}
func main() {
car := Car{Model: "Audi"}
car.SetModel("BMW")
fmt.Println(car.Model) // Print Audi
}
package main
import "fmt"
type Car struct {
Model string
}
func (c *Car) SetModel(model string) {
c.Model = model
}
func main() {
car := Car{Model: "Audi"}
car.SetModel("BMW")
fmt.Println(car.Model) // Print BMW
}
Gotcha
package main
import "fmt"
func main() {
x := 1
fmt.Println(x)
{
fmt.Println(x)
x := 2
fmt.Println(x)
}
fmt.Println(x)
}
Gotcha
package main
import "fmt"
func main() {
x := 1
fmt.Println(x)
{
fmt.Println(x)
x := 2
fmt.Println(x)
}
fmt.Println(x)
}
$ go run main.go
1
1
2
1
Gotcha
package main
import "fmt"
func main() {
p := person{"john", 15}
defer printPerson(p)
updateAge(&p, 20)
}
type person struct {
name string
age int
}
func printPerson(p person) {
fmt.Printf("Name: %s, Age: %d", p.name, p.age)
}
func updateAge(p *person, newAge int) {
p.age = newAge
}
Gotcha
package main
import "fmt"
func main() {
p := person{"john", 15}
defer printPerson(p)
updateAge(&p, 20)
}
type person struct {
name string
age int
}
func printPerson(p person) {
fmt.Printf("Name: %s, Age: %d", p.name, p.age)
}
func updateAge(p *person, newAge int) {
p.age = newAge
}
$ go run main.go
Name: john, Age: 15
Questions?
Thank you

More Related Content

What's hot

Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In PythonMarwan Osman
 
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&CoMail.ru Group
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinAhmad Arif Faizin
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MoreMatt Harrison
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the pointseanmcq
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script ProgrammingLin Yo-An
 
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
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxEleanor McHugh
 
Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin IGuixing Bai
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)Matt Harrison
 
Migrations With Transmogrifier
Migrations With TransmogrifierMigrations With Transmogrifier
Migrations With TransmogrifierRok Garbas
 
Migrating from drupal to plone with transmogrifier
Migrating from drupal to plone with transmogrifierMigrating from drupal to plone with transmogrifier
Migrating from drupal to plone with transmogrifierClayton Parker
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windowsextremecoders
 
Laying Pipe with Transmogrifier
Laying Pipe with TransmogrifierLaying Pipe with Transmogrifier
Laying Pipe with TransmogrifierClayton Parker
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Qiangning Hong
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5PyNSK
 
7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)Steven Francia
 

What's hot (20)

Programming Under Linux In Python
Programming Under Linux In PythonProgramming Under Linux In Python
Programming Under Linux In Python
 
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
«iPython & Jupyter: 4 fun & profit», Лев Тонких, Rambler&Co
 
Dts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlinDts x dicoding #2 memulai pemrograman kotlin
Dts x dicoding #2 memulai pemrograman kotlin
 
PyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and MorePyCon 2013 : Scripting to PyPi to GitHub and More
PyCon 2013 : Scripting to PyPi to GitHub and More
 
Biopython
BiopythonBiopython
Biopython
 
Gevent what's the point
Gevent what's the pointGevent what's the point
Gevent what's the point
 
Vim Script Programming
Vim Script ProgrammingVim Script Programming
Vim Script Programming
 
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
 
Implementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 reduxImplementing virtual machines in go & c 2018 redux
Implementing virtual machines in go & c 2018 redux
 
Python and sysadmin I
Python and sysadmin IPython and sysadmin I
Python and sysadmin I
 
Why Python (for Statisticians)
Why Python (for Statisticians)Why Python (for Statisticians)
Why Python (for Statisticians)
 
Migrations With Transmogrifier
Migrations With TransmogrifierMigrations With Transmogrifier
Migrations With Transmogrifier
 
Txjs
TxjsTxjs
Txjs
 
Migrating from drupal to plone with transmogrifier
Migrating from drupal to plone with transmogrifierMigrating from drupal to plone with transmogrifier
Migrating from drupal to plone with transmogrifier
 
Reversing the dropbox client on windows
Reversing the dropbox client on windowsReversing the dropbox client on windows
Reversing the dropbox client on windows
 
Laying Pipe with Transmogrifier
Laying Pipe with TransmogrifierLaying Pipe with Transmogrifier
Laying Pipe with Transmogrifier
 
Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010Python于Web 2.0网站的应用 - QCon Beijing 2010
Python于Web 2.0网站的应用 - QCon Beijing 2010
 
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
Commit ускоривший python 2.7.11 на 30% и новое в python 3.5
 
Golang Channels
Golang ChannelsGolang Channels
Golang Channels
 
7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)7 Common Mistakes in Go (2015)
7 Common Mistakes in Go (2015)
 

Similar to Geeks Anonymes - Le langage 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 1Robert Stern
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersAlessandro Sanino
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMRaveen Perera
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptxGuy Komari
 
Scaling FastAGI Applications with Go
Scaling FastAGI Applications with GoScaling FastAGI Applications with Go
Scaling FastAGI Applications with GoDigium
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with goHean Hong Leong
 
Introduction to go
Introduction to goIntroduction to go
Introduction to goJaehue Jang
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageDroidConTLV
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my dayTor Ivry
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)Pavlo Baron
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of GoFrank Müller
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs偉格 高
 
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija SiskoTrivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija SiskoTrivadis
 
Go programming introduction
Go programming introductionGo programming introduction
Go programming introductionGinto Joseph
 
To GO or not to GO
To GO or not to GOTo GO or not to GO
To GO or not to GOsuperstas88
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Samuel Lampa
 
Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programmingMahmoud Masih Tehrani
 

Similar to Geeks Anonymes - Le langage Go (20)

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
 
The GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
 
Coding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBMCoding in GO - GDG SL - NSBM
Coding in GO - GDG SL - NSBM
 
golang_getting_started.pptx
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
 
Scaling FastAGI Applications with Go
Scaling FastAGI Applications with GoScaling FastAGI Applications with Go
Scaling FastAGI Applications with Go
 
Go serving: Building server app with go
Go serving: Building server app with goGo serving: Building server app with go
Go serving: Building server app with go
 
Introduction to go
Introduction to goIntroduction to go
Introduction to go
 
ProgrammingwithGOLang
ProgrammingwithGOLangProgrammingwithGOLang
ProgrammingwithGOLang
 
What's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritageWhat's in Kotlin for us - Alexandre Greschon, MyHeritage
What's in Kotlin for us - Alexandre Greschon, MyHeritage
 
Go ahead, make my day
Go ahead, make my dayGo ahead, make my day
Go ahead, make my day
 
What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)What can be done with Java, but should better be done with Erlang (@pavlobaron)
What can be done with Java, but should better be done with Erlang (@pavlobaron)
 
Beauty and Power of Go
Beauty and Power of GoBeauty and Power of Go
Beauty and Power of Go
 
Functional programming using underscorejs
Functional programming using underscorejsFunctional programming using underscorejs
Functional programming using underscorejs
 
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija SiskoTrivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
Trivadis TechEvent 2016 Go - The Cloud Programming Language by Andija Sisko
 
Go programming introduction
Go programming introductionGo programming introduction
Go programming introduction
 
To GO or not to GO
To GO or not to GOTo GO or not to GO
To GO or not to GO
 
Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...Using Flow-based programming to write tools and workflows for Scientific Comp...
Using Flow-based programming to write tools and workflows for Scientific Comp...
 
Gore: Go REPL
Gore: Go REPLGore: Go REPL
Gore: Go REPL
 
Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programming
 
Golang勉強会
Golang勉強会Golang勉強会
Golang勉強会
 

More from Geeks Anonymes

Programmer sous Unreal Engine
Programmer sous Unreal EngineProgrammer sous Unreal Engine
Programmer sous Unreal EngineGeeks Anonymes
 
Implémentation efficace et durable de processus métiers complexes
Implémentation efficace et durable de processus métiers complexesImplémentation efficace et durable de processus métiers complexes
Implémentation efficace et durable de processus métiers complexesGeeks Anonymes
 
Managing Open Source Licenses (Geeks Anonymes)
Managing Open Source Licenses (Geeks Anonymes)Managing Open Source Licenses (Geeks Anonymes)
Managing Open Source Licenses (Geeks Anonymes)Geeks Anonymes
 
Reprendre le contrôle de ses données
Reprendre le contrôle de ses donnéesReprendre le contrôle de ses données
Reprendre le contrôle de ses donnéesGeeks Anonymes
 
Le rôle du testeur et le Blackbox testing
Le rôle du testeur et le Blackbox testingLe rôle du testeur et le Blackbox testing
Le rôle du testeur et le Blackbox testingGeeks Anonymes
 
Vulnérabilités au cœur des applications Web, menaces et contre-mesures
 Vulnérabilités au cœur des applications Web, menaces et contre-mesures Vulnérabilités au cœur des applications Web, menaces et contre-mesures
Vulnérabilités au cœur des applications Web, menaces et contre-mesuresGeeks Anonymes
 
191121 philippe teuwen cryptographie et attaques materielles
191121 philippe teuwen cryptographie et attaques materielles191121 philippe teuwen cryptographie et attaques materielles
191121 philippe teuwen cryptographie et attaques materiellesGeeks Anonymes
 
"Surfez couverts !" - Conseils de Cyber securité
"Surfez couverts !" - Conseils de Cyber securité "Surfez couverts !" - Conseils de Cyber securité
"Surfez couverts !" - Conseils de Cyber securité Geeks Anonymes
 
Introduction au développement mobile - développer une application iOS et Andr...
Introduction au développement mobile - développer une application iOS et Andr...Introduction au développement mobile - développer une application iOS et Andr...
Introduction au développement mobile - développer une application iOS et Andr...Geeks Anonymes
 
Intelligence artificielle et propriété intellectuelle
Intelligence artificielle et propriété intellectuelleIntelligence artificielle et propriété intellectuelle
Intelligence artificielle et propriété intellectuelleGeeks Anonymes
 
Pour une histoire plophonique du jeu video
Pour une histoire plophonique du jeu videoPour une histoire plophonique du jeu video
Pour une histoire plophonique du jeu videoGeeks Anonymes
 
Become Rick and famous, thanks to Open Source
Become Rick and famous, thanks to Open SourceBecome Rick and famous, thanks to Open Source
Become Rick and famous, thanks to Open SourceGeeks Anonymes
 
Reconnaissance vocale et création artistique
Reconnaissance vocale et création artistiqueReconnaissance vocale et création artistique
Reconnaissance vocale et création artistiqueGeeks Anonymes
 
Natural Language Processing
Natural Language ProcessingNatural Language Processing
Natural Language ProcessingGeeks Anonymes
 
Sécurité, GDPR : vos données ont de la valeur
Sécurité, GDPR : vos données ont de la valeur Sécurité, GDPR : vos données ont de la valeur
Sécurité, GDPR : vos données ont de la valeur Geeks Anonymes
 

More from Geeks Anonymes (20)

Programmer sous Unreal Engine
Programmer sous Unreal EngineProgrammer sous Unreal Engine
Programmer sous Unreal Engine
 
Implémentation efficace et durable de processus métiers complexes
Implémentation efficace et durable de processus métiers complexesImplémentation efficace et durable de processus métiers complexes
Implémentation efficace et durable de processus métiers complexes
 
Managing Open Source Licenses (Geeks Anonymes)
Managing Open Source Licenses (Geeks Anonymes)Managing Open Source Licenses (Geeks Anonymes)
Managing Open Source Licenses (Geeks Anonymes)
 
Reprendre le contrôle de ses données
Reprendre le contrôle de ses donnéesReprendre le contrôle de ses données
Reprendre le contrôle de ses données
 
Le rôle du testeur et le Blackbox testing
Le rôle du testeur et le Blackbox testingLe rôle du testeur et le Blackbox testing
Le rôle du testeur et le Blackbox testing
 
Kubernetes
KubernetesKubernetes
Kubernetes
 
Vulnérabilités au cœur des applications Web, menaces et contre-mesures
 Vulnérabilités au cœur des applications Web, menaces et contre-mesures Vulnérabilités au cœur des applications Web, menaces et contre-mesures
Vulnérabilités au cœur des applications Web, menaces et contre-mesures
 
191121 philippe teuwen cryptographie et attaques materielles
191121 philippe teuwen cryptographie et attaques materielles191121 philippe teuwen cryptographie et attaques materielles
191121 philippe teuwen cryptographie et attaques materielles
 
"Surfez couverts !" - Conseils de Cyber securité
"Surfez couverts !" - Conseils de Cyber securité "Surfez couverts !" - Conseils de Cyber securité
"Surfez couverts !" - Conseils de Cyber securité
 
Introduction au développement mobile - développer une application iOS et Andr...
Introduction au développement mobile - développer une application iOS et Andr...Introduction au développement mobile - développer une application iOS et Andr...
Introduction au développement mobile - développer une application iOS et Andr...
 
Le langage rust
Le langage rustLe langage rust
Le langage rust
 
Test your code
Test your codeTest your code
Test your code
 
Intelligence artificielle et propriété intellectuelle
Intelligence artificielle et propriété intellectuelleIntelligence artificielle et propriété intellectuelle
Intelligence artificielle et propriété intellectuelle
 
Pour une histoire plophonique du jeu video
Pour une histoire plophonique du jeu videoPour une histoire plophonique du jeu video
Pour une histoire plophonique du jeu video
 
Become Rick and famous, thanks to Open Source
Become Rick and famous, thanks to Open SourceBecome Rick and famous, thanks to Open Source
Become Rick and famous, thanks to Open Source
 
Reconnaissance vocale et création artistique
Reconnaissance vocale et création artistiqueReconnaissance vocale et création artistique
Reconnaissance vocale et création artistique
 
Natural Language Processing
Natural Language ProcessingNatural Language Processing
Natural Language Processing
 
Sécurité, GDPR : vos données ont de la valeur
Sécurité, GDPR : vos données ont de la valeur Sécurité, GDPR : vos données ont de la valeur
Sécurité, GDPR : vos données ont de la valeur
 
Modern sql
Modern sqlModern sql
Modern sql
 
Qt
QtQt
Qt
 

Recently uploaded

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️anilsa9823
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 

Recently uploaded (20)

A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online  ☂️
CALL ON ➥8923113531 🔝Call Girls Kakori Lucknow best sexual service Online ☂️
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 

Geeks Anonymes - Le langage Go

  • 1. Geek Anonyme - 23/09/2020 Thomas Hayen - Gabismartcare
  • 2. Agenda - Introduction - Why and What is Go? - Small tour
  • 4. Who am I? - Thomas Hayen - Computer engineer ULg 2010 - Java developer since 2010 - Go developer since 2019
  • 5. Java? Back to 2019… Goals: - Event sourced architecture - Cloud based (Docker, Kubernetes,...) - Micro services - database(s) - Messaging system
  • 6. Java? First version - 6 microservices just running (no clients) - > 1Gb memory RAM - CPU usage >5% - Images docker +/- 150Mo /container - Starting time +/- 2 sec container (5 sec if docker is not spawned)
  • 7. Let’s try Go - 6 microservices just running (no clients) - < 20 Mb memory RAM - CPU usage < 1% - Images docker +/- 5Mo /container - Starting time < 1 sec container (2 sec if docker is not spawned)
  • 8. $ docker images geek/go-hello latest 760ba5405773 4.78MB geek/spring-hello latest a224fb9bc642 121MB $ docker stats CONTAINER ID NAME CPU % MEM USAGE / LIMIT MEM % e680f347aee5 JAVA 0.09% 200.6MiB / 23.12GiB 0.85% 3061e909e394 GO 0.00% 1.812MiB / 23.12GiB 0.01% Docker image comparison
  • 9. WHY Go AND WHAT IS Go?
  • 10. Why Go? - Complexity required to use languages - Processors are multi-core, most languages offered little help to program them efficiently and safely. - Frustration with existing languages: one had to choose either efficient compilation, efficient execution, or ease of programming - slow builds - uncontrolled dependencies - each programmer using a different subset of the language - poor program understanding (code hard to read, poorly documented, and so on) - ... https://talks.golang.org/2012/splash.article
  • 11. Go Spec - C like - Network (web app, …) - Multiprocessor - Scaling (in term of dependency and build) - Easy to use
  • 12. What is Go? - Designed at Google by Robert Griesemer, Rob Pike and Ken Thompson - Compiled, - Concurrent, - Garbage-collected, - Statically typed language - Fast build - Simple - Great environment
  • 14. So let’s Go - Hello world... // create package main every program will be in package main and have a main function package main // import keyword is used to import "fmt" in your package import "fmt" // func is used to create function entry point func main() { hello := "Hello world" fmt.Println(hello) }
  • 15. Sample example //main.go package main func sum(a, b int) int { return a + b }
  • 16. Testing //main_test.go package main import "testing" func TestSum(t *testing.T) { if 2 != sum(1,1) { t.Errorf("Error 1+1 should be 2") } }
  • 17. Testing func TestMultipleInputOutput(t *testing.T) { tests := []struct { name string input1, input2, expected int }{ {name: "1+1=2", input1: 1, input2: 1, expected: 2}, {name: "5+5=10", input1: 5, input2: 5, expected: 10}, {name: "-1-0=-1", input1: -1, input2: 0, expected: 3}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { value := sum(tt.input1, tt.input2) if value != tt.expected { t.Errorf("%d + %d should be %d, got %d", tt.input1, tt.input2, tt.expected, value) } }) } }
  • 18. Testing $ go test -v * === RUN TestMultipleInputOutput === RUN TestMultipleInputOutput/1+1=2 === RUN TestMultipleInputOutput/5+5=10 === RUN TestMultipleInputOutput/-1-0=-1 main_test.go:17: -1 + 0 should be 3, got -1 --- FAIL: TestMultipleInputOutput (0.00s) --- PASS: TestMultipleInputOutput/1+1=2 (0.00s) --- PASS: TestMultipleInputOutput/5+5=10 (0.00s) --- FAIL: TestMultipleInputOutput/-1-0=-1 (0.00s) FAIL FAIL command-line-arguments 0.002s FAIL
  • 19. A more complete example package main import ( "fmt" random "math/rand" "time" ) import "errors" // Upper first letters are exported var ( NonExistingError = errors.New("NonExistingError") NonExistingError2 = errors.New("NonExistingError2") NonExistingError3 = errors.New("NonExistingError3") ) // Lower letters not const ( lowerCaseLetters = "abcdefghijklmnopqrstuvwxyz" )
  • 20. A more complete example func main() { inputArray, err := generateSliceOfRandomString(10) checkError(err) fmt.Println(inputArray) quicksort(inputArray, 0, len(inputArray)-1) for i, s := range inputArray { fmt.Println(fmt.Sprintf("At index %d, found %s", i, s)) } }
  • 21. A more complete example func checkError(err error) { if err != nil { switch err { case NonExistingError: fmt.Println("This is an NonExistingError") case NonExistingError2: fallthrough case NonExistingError3: fmt.Println("This is an NonExistingError2 or 3") default: panic(err) } } }
  • 22. A more complete example func generateSliceOfRandomString(size int) ([]string, error) { startingTime := time.Now() defer printDuration(startingTime) // defer rand.Seed(startingTime.UnixNano()) var slice []string = make([]string, size) // slice time.Sleep(1 * time.Second) for i := 0; i < size; i++ { b := make([]byte, 16) for i := range b { b[i] = lowerCaseLetters[random.Intn(len(lowerCaseLetters))] //Renamed in imports } slice[i] = string(b) } return slice, nil } func printDuration(startingTime time.Time) { fmt.Println("Execution time: ", time.Now().Sub(startingTime)) }
  • 23. A more complete example func quicksort(arr []string, start, end int) { if (end - start) < 1 { return } pivot := arr[end] splitIndex := start for i := start; i < end; i++ { if arr[i] < pivot { arr[splitIndex], arr[i] = arr[i], arr[splitIndex] splitIndex++ } } arr[end], arr[splitIndex] = arr[splitIndex], pivot quicksort(arr, start, splitIndex-1) quicksort(arr, splitIndex+1, end) }
  • 24. Output $ go run main.go Execution time: 1.000107637s [uovedvemekymaops xrlzrshegtbdnows enhwynbzqfjpbmpq lhuxkoryozievjiu ecomkhxglzxdjngf kipvolyziwfagacv knyjxajpcspjgkbc jthfcayshhotvcxj wipxnhtaoqlgtjsk oabiguaudkzryxfn] At index 0, found ecomkhxglzxdjngf At index 1, found enhwynbzqfjpbmpq At index 2, found jthfcayshhotvcxj At index 3, found kipvolyziwfagacv At index 4, found knyjxajpcspjgkbc At index 5, found lhuxkoryozievjiu At index 6, found oabiguaudkzryxfn At index 7, found uovedvemekymaops At index 8, found wipxnhtaoqlgtjsk At index 9, found xrlzrshegtbdnows
  • 25. Go concurrency func main() { inputArray, _ := generateSlice(100) wg := sync.WaitGroup{} fmt.Println(inputArray) quicksortConcurrent(wg, inputArray, 0, len(inputArray)-1) wg.Wait() fmt.Println("Finished") for i, s := range inputArray { fmt.Println(fmt.Sprintf("At index %d, found %s", i, s)) } } func quicksortConcurrent(wg sync.WaitGroup,arr []string,start,end int){ wg.Add(1) defer wg.Done() if (end - start) < 1 { return } pivot := arr[end] splitIndex := start for i := start; i < end; i++ { if arr[i] < pivot { arr[splitIndex], arr[i] = arr[i], arr[splitIndex] splitIndex++ } } arr[end], arr[splitIndex] = arr[splitIndex], pivot go quicksortConcurrent(wg, arr, start, splitIndex-1) go quicksortConcurrent(wg, arr, splitIndex+1, end) }
  • 26. Benchmark… Yet another Go feature... package main import ( "sync" "testing" ) var inputArray []string func init() { inputArray, _ = generateSlice(500) } func BenchmarkFuncNormal(b *testing.B) { for i := 0; i < b.N; i++ { quicksort(inputArray, 0, len(inputArray)-1) } } func BenchmarkFuncConcurrent(b *testing.B) { for i := 0; i < b.N; i++ { quicksortConcurrent(sync.WaitGroup{}, inputArray, 0, len(inputArray)-1) } }
  • 27. Let’s compare executions $ go test -bench=. goos: linux goarch: amd64 pkg: geek BenchmarkFuncNormal-4 862 1415186 ns/op BenchmarkFuncConcurrent-4 10000 484759 ns/op PASS ok geek 7.233s
  • 28. Go Channels package main import "fmt" func sum(s []int, c chan int) { sum := 0 for _, v := range s { sum += v } c <- sum // send sum to c } func main() { s := []int{7, 2, 8, -9, 4, 0} c := make(chan int) go sum(s[:len(s)/2], c) go sum(s[len(s)/2:], c) x, y := <-c, <-c // receive from c fmt.Println(x, y, x+y) } $ go run main.go -5 17 12
  • 29. Go dependency go.mod module geek go 1.15 require ( cloud.google.com/go/firestore v1.3.0 github.com/lib/pq v1.8.0 ) $ go mod download $ go get github.com/lib/pq
  • 30. Is Go an object oriented language? We can define structure and apply method on it type Animal struct { Name string // This is public surname string // This is “private” } func (Animal) Speak() { fmt.Println("I'm an animal") } func main() { _ = Animal{ Name: "name", surname: "Surname", } a := Animal{"name","surname"} //Work but not recommended a.Speak() }
  • 31. Is Go an object oriented language? There is also a way to embed types type Dog struct { Animal } func main() { dog := Dog{ Animal{ Name: "Name", Surname: "SurName", }, } dog.Name = "dog name" dog.Speak() //Print I'm an animal }
  • 32. Is Go an object oriented language? We can override method func (d Dog) Speak() { fmt.Println(fmt.Sprintf("I'm an dog and my name is %s", d.Name)); } func main() { dog := Dog{} dog.Speak() //Print I'm a dog and my name is }
  • 33. Is Go an object oriented language? But… func main() { dog := Dog{} animals := []Animal{} animals = append(animals, dog) //Cannot use 'dog' (type Dog) as type Animal }
  • 34. Is Go an object oriented language? Solution type Speaker interface { Speak() } func main() { dog := Dog{} animals := []Speaker{} animals = append(animals, dog) for _, animal := range animals { animal.Speak() //Print I'm an dog and my name is } }
  • 35. Go has pointer package main import "fmt" type Car struct { Model string } func main() { car := Car{Model: "Audi"} ptrOnCar := &car fmt.Println((*ptrOnCar).Model) // Print Audi fmt.Println(ptrOnCar.Model) // Print Audi }
  • 36. Go pass by value package main import "fmt" type Car struct { Model string } func (c Car) SetModel(model string) { c.Model = model } func main() { car := Car{Model: "Audi"} car.SetModel("BMW") fmt.Println(car.Model) // Print Audi } package main import "fmt" type Car struct { Model string } func (c *Car) SetModel(model string) { c.Model = model } func main() { car := Car{Model: "Audi"} car.SetModel("BMW") fmt.Println(car.Model) // Print BMW }
  • 37. Gotcha package main import "fmt" func main() { x := 1 fmt.Println(x) { fmt.Println(x) x := 2 fmt.Println(x) } fmt.Println(x) }
  • 38. Gotcha package main import "fmt" func main() { x := 1 fmt.Println(x) { fmt.Println(x) x := 2 fmt.Println(x) } fmt.Println(x) } $ go run main.go 1 1 2 1
  • 39. Gotcha package main import "fmt" func main() { p := person{"john", 15} defer printPerson(p) updateAge(&p, 20) } type person struct { name string age int } func printPerson(p person) { fmt.Printf("Name: %s, Age: %d", p.name, p.age) } func updateAge(p *person, newAge int) { p.age = newAge }
  • 40. Gotcha package main import "fmt" func main() { p := person{"john", 15} defer printPerson(p) updateAge(&p, 20) } type person struct { name string age int } func printPerson(p person) { fmt.Printf("Name: %s, Age: %d", p.name, p.age) } func updateAge(p *person, newAge int) { p.age = newAge } $ go run main.go Name: john, Age: 15