SlideShare uma empresa Scribd logo
1 de 69
Go. Why it goes?
About me
Serhii Pichkurov
◎5+ years of experience
◎Java
◎Mostly backend
◎No experience as presenter
before
◎9 months with Go
Agenda
❑ Go is not C, not Java, not anything
❑ Gopher
❑ Rob Pike argument
❑ Main ideas
❑ Concurrency model
❑ Tools
❑ Issues and gotchas
Characteristics
Go (often referred to as golang) is:
◎Clean procedural language designed
for scalable cloud software
◎open source
◎statically typed with duck typing
Characteristics
◎CSP(communicating sequential
processes) as concurrent model
◎with garbage collection
◎created at Google in 2007 by
Robert Griesemer(V8), Rob
Pike(UNIX, UTF-8), and Ken
Thompson(UNIX, regexp)
Characteristics
◎compiled
◎two compilers: "gc"(many platforms
including smartphones) and
“gccgo”(more optimizations, more
processors)
◎Linux, OS X, FreeBSD, Windows and
more
Motivated by Google’s needs:
● Efficiency
● Safety
● Concurrency
● Scalability
● Fast development cycle
● No surprises
● A cute mascot
Why new
lang?
Who uses Go at
Google?
Lots of projects. Thousands of Go
programmers. Millions of lines of Go code.
Public examples:
◎ Kubernetes
◎ SPDY proxy for Chrome on mobile
devices
◎ dl.google.com is written in Go
◎ YouTube Vitess MySQL balancer
Who uses Go besides
Google?
Products written in Go
Go use-cases
◎ Cloud/Networking - routers,
proxies, etc
◎ Distributed services and
storages
◎ Internal infrastructures
◎ Microservices (with frameworks,
like GoKit)
◎ Containers and orchestration
◎ Command-line tools
Mascot: the gopher
Rob Pike
Active Development
GC in Go
GC in Go 1.6
Rob Pike argument
● Go is different
● Go does not try to be like the other
languages
● Go does not compete on features
● As of Go 1, the language is fixed
Everything is
passed by value
Go elements
● concrete data types
● functions and methods
● interfaces
● structs
● packages
● concurrency
● Plus: Good tools, fast builds.
● All the pieces feel simple in practice.
Types
◎bool
◎string
◎int int8 int16 int32 int64
uint uint8 uint16 uint32 uint64
◎byte //alias for uint8
◎rune //alias for int32, Unicode char
◎float32 float64
◎complex32 complex64
Arrays
An array's length is part of its type, so arrays
cannot be resized.
var arr [5]int
arr[4] = 42
Slices
A slice, on the other hand, is a dynamically-sized,
flexible view(reference) into the elements of an array
bytes := [5]byte{} // array
var slice = bytes[2:4]
names := []string{"leto", "paul", "teg"}
c := make([]string, len(names))
copy(c, names)
names = append(names,"ioav")
Slices
foo = make([]int, 5)
foo[3] = 42
foo[4] = 100
Maps
m = make(map[string]int) // declare
m["route"] = 66 // put
i := m["route"] // get
delete(m, "route")
_, ok := m["route"] //check is present
for key, value := range m { //iterate
fmt.Println("Key:", key, "Value:", value)
}
commits := map[string]int{ //static population
"gri": 1908,
"adg": 912,
}
Maps
Important to remember: when no value is
assigned to key, zero value is returned
Interfaces
Just a set of methods. No data. Simple idea, but
more complex than expected.
type Reader interface {
Read(p []byte) (n int, err error)
}
_, err := reader.Read(p)
Structs
type Item struct {
Title string
URL string
}
item := Item{Title:"title",URL:"http:..."}
Pointers
A pointer holds the memory address of a variable.
The & operator generates a pointer to its operand.
i := 42
p = &i
The * operator denotes the pointer's underlying
value.
fmt.Println(*p) // read i through the pointer p
*p = 21 // set i through the pointer p
Tags aka annotations
type Person struct {
FirstName string `json:"first_name"`
LastName string `json:"last_name"`
MiddleName string
`json:"middle_name,omitempty"`
}
Demo
Packages
We can import one or more package, there are three
types: system, local and remote.
System – out of the box. Like http, testing, etc
Local – in your repository, no need to use full
path.
Remote – has complete import path pointing to
the server.
To import remote package:
import "github.com/nf/wav"
Getting dependencies
For remote package use go get to fetch into
workspace.
go get github.com/nf/wav
Other operations also done via go CLI tool:
go build
go test
go run
and more
Concurrency
Based on CSP that was first described in a 1978
paper by Tony Hoare.
Has three elements:
● coroutines (execution)
● channels (communication)
● select (coordination)
“
Don't communicate by
sharing memory, share
memory by communicating
Goroutines
Start a goroutine with the go keyword:
go function(args)
Like garbage collection, eliminate considerations
from the programmer's concern:
● no stack size
● no return or completion status
● no mechanism for management
● no "ID"
Goroutines
◎Goroutines are like lightweight threads.
◎Go programs can have hundreds of
thousands of them
◎The Go runtime schedules goroutines
onto OS threads
◎Blocked goroutines don't use a thread
Channels
Channels provide communication
between goroutines.
c := make(chan string)
// goroutine 1
c <- "hello!"
// goroutine 2
s := <-c
fmt.Println(s) // "hello!"
Select
A select statement blocks until one of its cases
can run, then it executes that case.
msg := "hi"
select {
case n := <-in:
fmt.Println("received", n)
case out <- msg:
fmt.Println("sent", msg)
}
Demo time
Go and Java have much
in common
◎ C family (imperative, braces)
◎ Statically typed
◎ Garbage collected
◎ Memory safe (nil references,
runtime bounds checks)
Go and Java have much
in common
◎ Variables are always initialized
(zero/nil/false)
◎ Methods
◎ Interfaces
◎ Type assertions (instanceof)
◎ Reflection
Go differs from Java in
several ways
◎ Programs compile to machine code. There's no VM.
◎ Statically linked binaries
◎ Control over memory layout
◎ Function values and lexical closures
◎ GC does not have compaction phase
◎ Multiply return
Go intentionally leaves
out many features
◎ No classes
◎ No constructors
◎ No inheritance
◎ No ‘implements’ keyword
◎ No final
◎ No exceptions
◎ No user-defined generics
Exceptions go away
◎No Exceptions by design
◎Handling with multiple return
◎Panic!
type error interface {
Error() string
}
Errors design
rpm, err := rpm.OpenPackageFile(localPath)
if err != nil {
log.Error("Failed to read RPM headers: %v",
err)
return
}
file, err = file.ReadAt(archiveHead,
int64(headerEnd))
if err != nil {
log.Error("Failed to read RPM head: %v",
err)
return
}
Tools
go get is great,
but we need
more
Vendoring
server-one uses the mux package in $GOPATH/src/github.com/gorilla/mux.
server-two uses the mux package in vendor.
$GOPATH
src/
server-one/
main.go (import "github.com/gorilla/mux")
server-two/
main.go (import "github.com/gorilla/mux")
vendor/
github.com/
gorilla/
mux/
...
Glide for Package
Management
◎ Semantic Versions and Ranges
◎ Git, Bzr, Hg, Svn
◎ Works with Go toolchain
◎ Leverages vendor directory
◎ Imports from Godep, GB, GPM, Gom
◎ Private Repos and Forks
Go tools support
◎go fmt
◎goimports
◎go lint or gometalinter
◎godoc lookups
◎go generate
◎many more
◎easy to write your own
IDE
There's no "Go IDE". Go tools meet you where
you are.
◎Eclipse
◎IntelliJ
◎Atom
◎Emacs
◎Vim
◎many others
My experience
Project that searches for vulnerabilities
inside artifacts
◎microservices
◎RabbitMQ
◎MongoDB/PostgreSQL
◎REST API
◎work with files and archives
◎Docker
◎34860 lines of code
Issues and gotchas
Pointers,
pointers to
pointers, more
pointers.
Nil pointer is
still there and
happens in
runtime
Unused variables
or imports —
compilation error
No generics
func foo() []interface{} {
return []int{1,2,3}
}
cannot use []int literal (type []int) as
type []interface {} in return argument
“
If you want to do something
expensive — do it explicitly
Intellij: Debug
works once in
a day, tests are
not debuggable
Missing Comma In
Multi-Line Slice,
Array, and Map
Literals
func main() {
x := []int{
1,
2 //error
}
_ = x
}
Summary
“
I’m impressed about how easy
people can pick it up and start
being productive in a project ,
it’s also very easy to deploy
David Cuadrado, Authy
Simple can be expressive
Simplicity is complicated but
the clarity is worth the fight
Thanks!
Any questions?

Mais conteúdo relacionado

Mais procurados

Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)Ishin Vin
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewMarkus Schneider
 
Why you should care about Go (Golang)
Why you should care about Go (Golang)Why you should care about Go (Golang)
Why you should care about Go (Golang)Aaron Schlesinger
 
Go language presentation
Go language presentationGo language presentation
Go language presentationparamisoft
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go langAmal Mohan N
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageAniruddha Chakrabarti
 
Golang (Go Programming Language)
Golang (Go Programming Language)Golang (Go Programming Language)
Golang (Go Programming Language)ShubhamMishra485
 
Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go languageTzar Umang
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practiceGuilherme Garnier
 
Golang Restful 서버 개발기
Golang Restful 서버 개발기Golang Restful 서버 개발기
Golang Restful 서버 개발기Hyejong
 
Golang getting started
Golang getting startedGolang getting started
Golang getting startedHarshad Patil
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrencyjgrahamc
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in GolangOliver N
 

Mais procurados (20)

Go Programming Language (Golang)
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)
 
Golang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
 
Why you should care about Go (Golang)
Why you should care about Go (Golang)Why you should care about Go (Golang)
Why you should care about Go (Golang)
 
Go language presentation
Go language presentationGo language presentation
Go language presentation
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
 
GoLang Introduction
GoLang IntroductionGoLang Introduction
GoLang Introduction
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
 
Golang (Go Programming Language)
Golang (Go Programming Language)Golang (Go Programming Language)
Golang (Go Programming Language)
 
Introduction to Go language
Introduction to Go languageIntroduction to Go language
Introduction to Go language
 
Go lang
Go langGo lang
Go lang
 
Goroutines and Channels in practice
Goroutines and Channels in practiceGoroutines and Channels in practice
Goroutines and Channels in practice
 
Golang
GolangGolang
Golang
 
Golang Restful 서버 개발기
Golang Restful 서버 개발기Golang Restful 서버 개발기
Golang Restful 서버 개발기
 
Golang getting started
Golang getting startedGolang getting started
Golang getting started
 
Concurrency With Go
Concurrency With GoConcurrency With Go
Concurrency With Go
 
Go Language presentation
Go Language presentationGo Language presentation
Go Language presentation
 
Go Concurrency
Go ConcurrencyGo Concurrency
Go Concurrency
 
Golang workshop
Golang workshopGolang workshop
Golang workshop
 
Go Lang Tutorial
Go Lang TutorialGo Lang Tutorial
Go Lang Tutorial
 
Concurrency in Golang
Concurrency in GolangConcurrency in Golang
Concurrency in Golang
 

Destaque

Resumo ecossistemas fatores bioticos abio
Resumo ecossistemas fatores bioticos abioResumo ecossistemas fatores bioticos abio
Resumo ecossistemas fatores bioticos abioStéphanie Lima
 
《長照服務法》── 長照資源發展的根本大法
《長照服務法》── 長照資源發展的根本大法《長照服務法》── 長照資源發展的根本大法
《長照服務法》── 長照資源發展的根本大法peter72401
 
Leaping the Barriers to Perfect Cash Forecating
Leaping the Barriers to Perfect Cash ForecatingLeaping the Barriers to Perfect Cash Forecating
Leaping the Barriers to Perfect Cash ForecatingElena Oliveira
 
Ask the Expert: The Hazardous Waste Generator Improvements Rule
Ask the Expert: The Hazardous Waste Generator Improvements RuleAsk the Expert: The Hazardous Waste Generator Improvements Rule
Ask the Expert: The Hazardous Waste Generator Improvements RuleTriumvirate Environmental
 
ARTIFICIAL INTELLIGENCE: The Future of Business.
 ARTIFICIAL INTELLIGENCE: The Future of Business.  ARTIFICIAL INTELLIGENCE: The Future of Business.
ARTIFICIAL INTELLIGENCE: The Future of Business. Diego Saenz
 
خلاقیت در نقاشی کودک
خلاقیت در نقاشی کودکخلاقیت در نقاشی کودک
خلاقیت در نقاشی کودکمشاور کودک
 
Presentation de la france
Presentation de la francePresentation de la france
Presentation de la francecaro AZERTY
 
Conheça me - rafael alves cordeiro
Conheça me - rafael alves cordeiroConheça me - rafael alves cordeiro
Conheça me - rafael alves cordeiroRafael Cordeiro
 

Destaque (16)

Carte complete gb 17.02.17
Carte complete gb 17.02.17Carte complete gb 17.02.17
Carte complete gb 17.02.17
 
Resumo ecossistemas fatores bioticos abio
Resumo ecossistemas fatores bioticos abioResumo ecossistemas fatores bioticos abio
Resumo ecossistemas fatores bioticos abio
 
Actividad uno
Actividad unoActividad uno
Actividad uno
 
《長照服務法》── 長照資源發展的根本大法
《長照服務法》── 長照資源發展的根本大法《長照服務法》── 長照資源發展的根本大法
《長照服務法》── 長照資源發展的根本大法
 
Carte complete fr 17.02.17
Carte complete fr 17.02.17Carte complete fr 17.02.17
Carte complete fr 17.02.17
 
Actividad leyes y normativa
Actividad leyes y normativaActividad leyes y normativa
Actividad leyes y normativa
 
Technical Report
Technical ReportTechnical Report
Technical Report
 
MINISTERIO JUVENIL ASOCENTRO
MINISTERIO JUVENIL ASOCENTROMINISTERIO JUVENIL ASOCENTRO
MINISTERIO JUVENIL ASOCENTRO
 
Leaping the Barriers to Perfect Cash Forecating
Leaping the Barriers to Perfect Cash ForecatingLeaping the Barriers to Perfect Cash Forecating
Leaping the Barriers to Perfect Cash Forecating
 
Ask the Expert: The Hazardous Waste Generator Improvements Rule
Ask the Expert: The Hazardous Waste Generator Improvements RuleAsk the Expert: The Hazardous Waste Generator Improvements Rule
Ask the Expert: The Hazardous Waste Generator Improvements Rule
 
ARTIFICIAL INTELLIGENCE: The Future of Business.
 ARTIFICIAL INTELLIGENCE: The Future of Business.  ARTIFICIAL INTELLIGENCE: The Future of Business.
ARTIFICIAL INTELLIGENCE: The Future of Business.
 
Internet y sus problemas
Internet y sus problemasInternet y sus problemas
Internet y sus problemas
 
خلاقیت در نقاشی کودک
خلاقیت در نقاشی کودکخلاقیت در نقاشی کودک
خلاقیت در نقاشی کودک
 
Presentation de la france
Presentation de la francePresentation de la france
Presentation de la france
 
Conheça me - rafael alves cordeiro
Conheça me - rafael alves cordeiroConheça me - rafael alves cordeiro
Conheça me - rafael alves cordeiro
 
Bulletin 2 17-17
Bulletin 2 17-17Bulletin 2 17-17
Bulletin 2 17-17
 

Semelhante a Go. Why it goes

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
 
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
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io
 
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
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsOWASP Kyiv
 
Golang Project Layout and Practice
Golang Project Layout and PracticeGolang Project Layout and Practice
Golang Project Layout and PracticeBo-Yi Wu
 
carrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIcarrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIYoni Davidson
 
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
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golangYoni Davidson
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGlobalLogic Ukraine
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016maiktoepfer
 
Improving go-git performance
Improving go-git performanceImproving go-git performance
Improving go-git performancesource{d}
 
go language- haseeb.pptx
go language- haseeb.pptxgo language- haseeb.pptx
go language- haseeb.pptxArsalanMaqsood1
 
Learning groovy -EU workshop
Learning groovy  -EU workshopLearning groovy  -EU workshop
Learning groovy -EU workshopadam1davis
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Jonathan Felch
 
Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016Codemotion
 
Golang workshop - Mindbowser
Golang workshop - MindbowserGolang workshop - Mindbowser
Golang workshop - MindbowserMindbowser Inc
 

Semelhante a Go. Why it goes (20)

Go. why it goes v2
Go. why it goes v2Go. why it goes v2
Go. why it goes v2
 
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
 
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
 
Mender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and GolangMender.io | Develop embedded applications faster | Comparing C and Golang
Mender.io | Develop embedded applications faster | Comparing C and Golang
 
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
 
Andriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
 
Golang Project Layout and Practice
Golang Project Layout and PracticeGolang Project Layout and Practice
Golang Project Layout and Practice
 
carrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-APIcarrow - Go bindings to Apache Arrow via C++-API
carrow - Go bindings to Apache Arrow via C++-API
 
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
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golang
 
Golang preso
Golang presoGolang preso
Golang preso
 
C++primer
C++primerC++primer
C++primer
 
Go Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii ShapovalGo Is Your Next Language — Sergii Shapoval
Go Is Your Next Language — Sergii Shapoval
 
Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016Not Your Fathers C - C Application Development In 2016
Not Your Fathers C - C Application Development In 2016
 
Improving go-git performance
Improving go-git performanceImproving go-git performance
Improving go-git performance
 
go language- haseeb.pptx
go language- haseeb.pptxgo language- haseeb.pptx
go language- haseeb.pptx
 
Learning groovy -EU workshop
Learning groovy  -EU workshopLearning groovy  -EU workshop
Learning groovy -EU workshop
 
Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)Groovy On Trading Desk (2010)
Groovy On Trading Desk (2010)
 
Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016Getting started with go - Florin Patan - Codemotion Milan 2016
Getting started with go - Florin Patan - Codemotion Milan 2016
 
Golang workshop - Mindbowser
Golang workshop - MindbowserGolang workshop - Mindbowser
Golang workshop - Mindbowser
 

Último

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024The Digital Insurer
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Zilliz
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native ApplicationsWSO2
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...apidays
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024The Digital Insurer
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsNanddeep Nachan
 

Último (20)

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
Emergent Methods: Multi-lingual narrative tracking in the news - real-time ex...
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
Apidays Singapore 2024 - Scalable LLM APIs for AI and Generative AI Applicati...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 

Go. Why it goes

  • 1. Go. Why it goes?
  • 2. About me Serhii Pichkurov ◎5+ years of experience ◎Java ◎Mostly backend ◎No experience as presenter before ◎9 months with Go
  • 3. Agenda ❑ Go is not C, not Java, not anything ❑ Gopher ❑ Rob Pike argument ❑ Main ideas ❑ Concurrency model ❑ Tools ❑ Issues and gotchas
  • 4. Characteristics Go (often referred to as golang) is: ◎Clean procedural language designed for scalable cloud software ◎open source ◎statically typed with duck typing
  • 5. Characteristics ◎CSP(communicating sequential processes) as concurrent model ◎with garbage collection ◎created at Google in 2007 by Robert Griesemer(V8), Rob Pike(UNIX, UTF-8), and Ken Thompson(UNIX, regexp)
  • 6. Characteristics ◎compiled ◎two compilers: "gc"(many platforms including smartphones) and “gccgo”(more optimizations, more processors) ◎Linux, OS X, FreeBSD, Windows and more
  • 7. Motivated by Google’s needs: ● Efficiency ● Safety ● Concurrency ● Scalability ● Fast development cycle ● No surprises ● A cute mascot Why new lang?
  • 8. Who uses Go at Google? Lots of projects. Thousands of Go programmers. Millions of lines of Go code. Public examples: ◎ Kubernetes ◎ SPDY proxy for Chrome on mobile devices ◎ dl.google.com is written in Go ◎ YouTube Vitess MySQL balancer
  • 9. Who uses Go besides Google?
  • 11. Go use-cases ◎ Cloud/Networking - routers, proxies, etc ◎ Distributed services and storages ◎ Internal infrastructures ◎ Microservices (with frameworks, like GoKit) ◎ Containers and orchestration ◎ Command-line tools
  • 16. GC in Go 1.6
  • 17. Rob Pike argument ● Go is different ● Go does not try to be like the other languages ● Go does not compete on features ● As of Go 1, the language is fixed
  • 19. Go elements ● concrete data types ● functions and methods ● interfaces ● structs ● packages ● concurrency ● Plus: Good tools, fast builds. ● All the pieces feel simple in practice.
  • 20. Types ◎bool ◎string ◎int int8 int16 int32 int64 uint uint8 uint16 uint32 uint64 ◎byte //alias for uint8 ◎rune //alias for int32, Unicode char ◎float32 float64 ◎complex32 complex64
  • 21. Arrays An array's length is part of its type, so arrays cannot be resized. var arr [5]int arr[4] = 42
  • 22. Slices A slice, on the other hand, is a dynamically-sized, flexible view(reference) into the elements of an array bytes := [5]byte{} // array var slice = bytes[2:4] names := []string{"leto", "paul", "teg"} c := make([]string, len(names)) copy(c, names) names = append(names,"ioav")
  • 23. Slices foo = make([]int, 5) foo[3] = 42 foo[4] = 100
  • 24. Maps m = make(map[string]int) // declare m["route"] = 66 // put i := m["route"] // get delete(m, "route") _, ok := m["route"] //check is present for key, value := range m { //iterate fmt.Println("Key:", key, "Value:", value) } commits := map[string]int{ //static population "gri": 1908, "adg": 912, }
  • 25. Maps Important to remember: when no value is assigned to key, zero value is returned
  • 26. Interfaces Just a set of methods. No data. Simple idea, but more complex than expected. type Reader interface { Read(p []byte) (n int, err error) } _, err := reader.Read(p)
  • 27. Structs type Item struct { Title string URL string } item := Item{Title:"title",URL:"http:..."}
  • 28. Pointers A pointer holds the memory address of a variable. The & operator generates a pointer to its operand. i := 42 p = &i The * operator denotes the pointer's underlying value. fmt.Println(*p) // read i through the pointer p *p = 21 // set i through the pointer p
  • 29. Tags aka annotations type Person struct { FirstName string `json:"first_name"` LastName string `json:"last_name"` MiddleName string `json:"middle_name,omitempty"` }
  • 30. Demo
  • 31. Packages We can import one or more package, there are three types: system, local and remote. System – out of the box. Like http, testing, etc Local – in your repository, no need to use full path. Remote – has complete import path pointing to the server. To import remote package: import "github.com/nf/wav"
  • 32. Getting dependencies For remote package use go get to fetch into workspace. go get github.com/nf/wav Other operations also done via go CLI tool: go build go test go run and more
  • 33.
  • 34. Concurrency Based on CSP that was first described in a 1978 paper by Tony Hoare. Has three elements: ● coroutines (execution) ● channels (communication) ● select (coordination)
  • 35. “ Don't communicate by sharing memory, share memory by communicating
  • 36. Goroutines Start a goroutine with the go keyword: go function(args) Like garbage collection, eliminate considerations from the programmer's concern: ● no stack size ● no return or completion status ● no mechanism for management ● no "ID"
  • 37. Goroutines ◎Goroutines are like lightweight threads. ◎Go programs can have hundreds of thousands of them ◎The Go runtime schedules goroutines onto OS threads ◎Blocked goroutines don't use a thread
  • 38. Channels Channels provide communication between goroutines. c := make(chan string) // goroutine 1 c <- "hello!" // goroutine 2 s := <-c fmt.Println(s) // "hello!"
  • 39. Select A select statement blocks until one of its cases can run, then it executes that case. msg := "hi" select { case n := <-in: fmt.Println("received", n) case out <- msg: fmt.Println("sent", msg) }
  • 41.
  • 42. Go and Java have much in common ◎ C family (imperative, braces) ◎ Statically typed ◎ Garbage collected ◎ Memory safe (nil references, runtime bounds checks)
  • 43. Go and Java have much in common ◎ Variables are always initialized (zero/nil/false) ◎ Methods ◎ Interfaces ◎ Type assertions (instanceof) ◎ Reflection
  • 44. Go differs from Java in several ways ◎ Programs compile to machine code. There's no VM. ◎ Statically linked binaries ◎ Control over memory layout ◎ Function values and lexical closures ◎ GC does not have compaction phase ◎ Multiply return
  • 45. Go intentionally leaves out many features ◎ No classes ◎ No constructors ◎ No inheritance ◎ No ‘implements’ keyword ◎ No final ◎ No exceptions ◎ No user-defined generics
  • 46. Exceptions go away ◎No Exceptions by design ◎Handling with multiple return ◎Panic! type error interface { Error() string }
  • 47. Errors design rpm, err := rpm.OpenPackageFile(localPath) if err != nil { log.Error("Failed to read RPM headers: %v", err) return } file, err = file.ReadAt(archiveHead, int64(headerEnd)) if err != nil { log.Error("Failed to read RPM head: %v", err) return }
  • 48. Tools
  • 49. go get is great, but we need more
  • 50. Vendoring server-one uses the mux package in $GOPATH/src/github.com/gorilla/mux. server-two uses the mux package in vendor. $GOPATH src/ server-one/ main.go (import "github.com/gorilla/mux") server-two/ main.go (import "github.com/gorilla/mux") vendor/ github.com/ gorilla/ mux/ ...
  • 51. Glide for Package Management ◎ Semantic Versions and Ranges ◎ Git, Bzr, Hg, Svn ◎ Works with Go toolchain ◎ Leverages vendor directory ◎ Imports from Godep, GB, GPM, Gom ◎ Private Repos and Forks
  • 52. Go tools support ◎go fmt ◎goimports ◎go lint or gometalinter ◎godoc lookups ◎go generate ◎many more ◎easy to write your own
  • 53. IDE There's no "Go IDE". Go tools meet you where you are. ◎Eclipse ◎IntelliJ ◎Atom ◎Emacs ◎Vim ◎many others
  • 54. My experience Project that searches for vulnerabilities inside artifacts ◎microservices ◎RabbitMQ ◎MongoDB/PostgreSQL ◎REST API ◎work with files and archives ◎Docker ◎34860 lines of code
  • 57. Nil pointer is still there and happens in runtime
  • 58. Unused variables or imports — compilation error
  • 60. func foo() []interface{} { return []int{1,2,3} } cannot use []int literal (type []int) as type []interface {} in return argument
  • 61. “ If you want to do something expensive — do it explicitly
  • 62. Intellij: Debug works once in a day, tests are not debuggable
  • 63. Missing Comma In Multi-Line Slice, Array, and Map Literals
  • 64. func main() { x := []int{ 1, 2 //error } _ = x }
  • 66. “ I’m impressed about how easy people can pick it up and start being productive in a project , it’s also very easy to deploy David Cuadrado, Authy
  • 67. Simple can be expressive
  • 68. Simplicity is complicated but the clarity is worth the fight