Go. Why it goes

Sergey Pichkurov
Sergey PichkurovSenior SE at Lohika
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
Go. Why it goes
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. Why it goes
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?
1 de 69

Recomendados

Golang por
GolangGolang
GolangSoftware Infrastructure
692 vistas48 diapositivas
Introduction to go lang por
Introduction to go langIntroduction to go lang
Introduction to go langAmal Mohan N
552 vistas40 diapositivas
Go Programming Language (Golang) por
Go Programming Language (Golang)Go Programming Language (Golang)
Go Programming Language (Golang)Ishin Vin
775 vistas40 diapositivas
Golang 101 por
Golang 101Golang 101
Golang 101宇 傅
2.5K vistas38 diapositivas
Go Language presentation por
Go Language presentationGo Language presentation
Go Language presentationGh-Mohammed Eldadah
581 vistas21 diapositivas
Golang por
GolangGolang
GolangFelipe Mamud
11.3K vistas52 diapositivas

Más contenido relacionado

La actualidad más candente

Introduction to Go programming language por
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming languageSlawomir Dorzak
5.7K vistas25 diapositivas
Go lang por
Go langGo lang
Go langSuelen Carvalho
8.3K vistas35 diapositivas
Coding with golang por
Coding with golangCoding with golang
Coding with golangHannahMoss14
320 vistas34 diapositivas
Golang (Go Programming Language) por
Golang (Go Programming Language)Golang (Go Programming Language)
Golang (Go Programming Language)ShubhamMishra485
1.9K vistas15 diapositivas
Introduction to Go language por
Introduction to Go languageIntroduction to Go language
Introduction to Go languageTzar Umang
1.1K vistas24 diapositivas
Go Programming Language by Google por
Go Programming Language by GoogleGo Programming Language by Google
Go Programming Language by GoogleUttam Gandhi
3.4K vistas20 diapositivas

La actualidad más candente(20)

Introduction to Go programming language por Slawomir Dorzak
Introduction to Go programming languageIntroduction to Go programming language
Introduction to Go programming language
Slawomir Dorzak5.7K vistas
Golang (Go Programming Language) por ShubhamMishra485
Golang (Go Programming Language)Golang (Go Programming Language)
Golang (Go Programming Language)
ShubhamMishra4851.9K vistas
Introduction to Go language por Tzar Umang
Introduction to Go languageIntroduction to Go language
Introduction to Go language
Tzar Umang1.1K vistas
Go Programming Language by Google por Uttam Gandhi
Go Programming Language by GoogleGo Programming Language by Google
Go Programming Language by Google
Uttam Gandhi3.4K vistas
Why you should care about Go (Golang) por Aaron Schlesinger
Why you should care about Go (Golang)Why you should care about Go (Golang)
Why you should care about Go (Golang)
Aaron Schlesinger1.6K vistas
The Go programming language - Intro by MyLittleAdventure por mylittleadventure
The Go programming language - Intro by MyLittleAdventureThe Go programming language - Intro by MyLittleAdventure
The Go programming language - Intro by MyLittleAdventure
mylittleadventure686 vistas
Introduction to GoLang por NVISIA
Introduction to GoLangIntroduction to GoLang
Introduction to GoLang
NVISIA351 vistas
Golang and Eco-System Introduction / Overview por Markus Schneider
Golang and Eco-System Introduction / OverviewGolang and Eco-System Introduction / Overview
Golang and Eco-System Introduction / Overview
Markus Schneider815 vistas
golang_getting_started.pptx por Guy Komari
golang_getting_started.pptxgolang_getting_started.pptx
golang_getting_started.pptx
Guy Komari99 vistas
GO programming language por tung vu
GO programming languageGO programming language
GO programming language
tung vu2.1K vistas

Destacado

Carte complete gb 17.02.17 por
Carte complete gb 17.02.17Carte complete gb 17.02.17
Carte complete gb 17.02.17Maison Tirel Guerin
93 vistas6 diapositivas
Resumo ecossistemas fatores bioticos abio por
Resumo ecossistemas fatores bioticos abioResumo ecossistemas fatores bioticos abio
Resumo ecossistemas fatores bioticos abioStéphanie Lima
147 vistas7 diapositivas
Actividad uno por
Actividad unoActividad uno
Actividad unoGabriela Díaz
44 vistas16 diapositivas
《長照服務法》── 長照資源發展的根本大法 por
《長照服務法》── 長照資源發展的根本大法《長照服務法》── 長照資源發展的根本大法
《長照服務法》── 長照資源發展的根本大法peter72401
247 vistas22 diapositivas
Carte complete fr 17.02.17 por
Carte complete fr 17.02.17Carte complete fr 17.02.17
Carte complete fr 17.02.17Maison Tirel Guerin
1.9K vistas6 diapositivas
Actividad leyes y normativa por
Actividad leyes y normativaActividad leyes y normativa
Actividad leyes y normativaleidy yohana Botero
97 vistas5 diapositivas

Destacado(16)

Resumo ecossistemas fatores bioticos abio por Stéphanie Lima
Resumo ecossistemas fatores bioticos abioResumo ecossistemas fatores bioticos abio
Resumo ecossistemas fatores bioticos abio
Stéphanie Lima147 vistas
《長照服務法》── 長照資源發展的根本大法 por peter72401
《長照服務法》── 長照資源發展的根本大法《長照服務法》── 長照資源發展的根本大法
《長照服務法》── 長照資源發展的根本大法
peter72401247 vistas
Leaping the Barriers to Perfect Cash Forecating por Elena Oliveira
Leaping the Barriers to Perfect Cash ForecatingLeaping the Barriers to Perfect Cash Forecating
Leaping the Barriers to Perfect Cash Forecating
Elena Oliveira970 vistas
ARTIFICIAL INTELLIGENCE: The Future of Business. por Diego Saenz
 ARTIFICIAL INTELLIGENCE: The Future of Business.  ARTIFICIAL INTELLIGENCE: The Future of Business.
ARTIFICIAL INTELLIGENCE: The Future of Business.
Diego Saenz1.2K vistas
Presentation de la france por caro AZERTY
Presentation de la francePresentation de la france
Presentation de la france
caro AZERTY258 vistas
Conheça me - rafael alves cordeiro por Rafael Cordeiro
Conheça me - rafael alves cordeiroConheça me - rafael alves cordeiro
Conheça me - rafael alves cordeiro
Rafael Cordeiro177 vistas

Similar a Go. Why it goes

Go. why it goes v2 por
Go. why it goes v2Go. why it goes v2
Go. why it goes v2Sergey Pichkurov
206 vistas72 diapositivas
The GO Language : From Beginners to Gophers por
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to GophersAlessandro Sanino
384 vistas55 diapositivas
Go 1.10 Release Party - PDX Go por
Go 1.10 Release Party - PDX GoGo 1.10 Release Party - PDX Go
Go 1.10 Release Party - PDX GoRodolfo Carvalho
344 vistas45 diapositivas
Mender.io | Develop embedded applications faster | Comparing C and Golang por
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
677 vistas34 diapositivas
10 reasons to be excited about go por
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about goDvir Volk
11.2K vistas33 diapositivas
Andriy Shalaenko - GO security tips por
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tipsOWASP Kyiv
1.5K vistas27 diapositivas

Similar a Go. Why it goes(20)

The GO Language : From Beginners to Gophers por Alessandro Sanino
The GO Language : From Beginners to GophersThe GO Language : From Beginners to Gophers
The GO Language : From Beginners to Gophers
Alessandro Sanino384 vistas
Mender.io | Develop embedded applications faster | Comparing C and Golang por Mender.io
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
Mender.io677 vistas
10 reasons to be excited about go por Dvir Volk
10 reasons to be excited about go10 reasons to be excited about go
10 reasons to be excited about go
Dvir Volk11.2K vistas
Andriy Shalaenko - GO security tips por OWASP Kyiv
Andriy Shalaenko - GO security tipsAndriy Shalaenko - GO security tips
Andriy Shalaenko - GO security tips
OWASP Kyiv1.5K vistas
Golang Project Layout and Practice por Bo-Yi Wu
Golang Project Layout and PracticeGolang Project Layout and Practice
Golang Project Layout and Practice
Bo-Yi Wu19.3K vistas
carrow - Go bindings to Apache Arrow via C++-API por Yoni Davidson
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
Yoni Davidson452 vistas
Golang basics for Java developers - Part 1 por Robert Stern
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
Robert Stern1.3K vistas
Not Your Fathers C - C Application Development In 2016 por maiktoepfer
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
maiktoepfer943 vistas
Improving go-git performance por source{d}
Improving go-git performanceImproving go-git performance
Improving go-git performance
source{d}266 vistas
Learning groovy -EU workshop por adam1davis
Learning groovy  -EU workshopLearning groovy  -EU workshop
Learning groovy -EU workshop
adam1davis282 vistas
Getting started with go - Florin Patan - Codemotion Milan 2016 por Codemotion
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
Codemotion871 vistas

Último

Black and White Modern Science Presentation.pptx por
Black and White Modern Science Presentation.pptxBlack and White Modern Science Presentation.pptx
Black and White Modern Science Presentation.pptxmaryamkhalid2916
16 vistas21 diapositivas
Report 2030 Digital Decade por
Report 2030 Digital DecadeReport 2030 Digital Decade
Report 2030 Digital DecadeMassimo Talia
15 vistas41 diapositivas
virtual reality.pptx por
virtual reality.pptxvirtual reality.pptx
virtual reality.pptxG036GaikwadSnehal
11 vistas15 diapositivas
PharoJS - Zürich Smalltalk Group Meetup November 2023 por
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023Noury Bouraqadi
126 vistas17 diapositivas
Perth MeetUp November 2023 por
Perth MeetUp November 2023 Perth MeetUp November 2023
Perth MeetUp November 2023 Michael Price
19 vistas44 diapositivas
ChatGPT and AI for Web Developers por
ChatGPT and AI for Web DevelopersChatGPT and AI for Web Developers
ChatGPT and AI for Web DevelopersMaximiliano Firtman
187 vistas82 diapositivas

Último(20)

Black and White Modern Science Presentation.pptx por maryamkhalid2916
Black and White Modern Science Presentation.pptxBlack and White Modern Science Presentation.pptx
Black and White Modern Science Presentation.pptx
maryamkhalid291616 vistas
Report 2030 Digital Decade por Massimo Talia
Report 2030 Digital DecadeReport 2030 Digital Decade
Report 2030 Digital Decade
Massimo Talia15 vistas
PharoJS - Zürich Smalltalk Group Meetup November 2023 por Noury Bouraqadi
PharoJS - Zürich Smalltalk Group Meetup November 2023PharoJS - Zürich Smalltalk Group Meetup November 2023
PharoJS - Zürich Smalltalk Group Meetup November 2023
Noury Bouraqadi126 vistas
Perth MeetUp November 2023 por Michael Price
Perth MeetUp November 2023 Perth MeetUp November 2023
Perth MeetUp November 2023
Michael Price19 vistas
Transcript: The Details of Description Techniques tips and tangents on altern... por BookNet Canada
Transcript: The Details of Description Techniques tips and tangents on altern...Transcript: The Details of Description Techniques tips and tangents on altern...
Transcript: The Details of Description Techniques tips and tangents on altern...
BookNet Canada135 vistas
Empathic Computing: Delivering the Potential of the Metaverse por Mark Billinghurst
Empathic Computing: Delivering  the Potential of the MetaverseEmpathic Computing: Delivering  the Potential of the Metaverse
Empathic Computing: Delivering the Potential of the Metaverse
Mark Billinghurst476 vistas
Business Analyst Series 2023 - Week 3 Session 5 por DianaGray10
Business Analyst Series 2023 -  Week 3 Session 5Business Analyst Series 2023 -  Week 3 Session 5
Business Analyst Series 2023 - Week 3 Session 5
DianaGray10237 vistas
Special_edition_innovator_2023.pdf por WillDavies22
Special_edition_innovator_2023.pdfSpecial_edition_innovator_2023.pdf
Special_edition_innovator_2023.pdf
WillDavies2217 vistas
Spesifikasi Lengkap ASUS Vivobook Go 14 por Dot Semarang
Spesifikasi Lengkap ASUS Vivobook Go 14Spesifikasi Lengkap ASUS Vivobook Go 14
Spesifikasi Lengkap ASUS Vivobook Go 14
Dot Semarang37 vistas
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas... por Bernd Ruecker
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
iSAQB Software Architecture Gathering 2023: How Process Orchestration Increas...
Bernd Ruecker33 vistas
DALI Basics Course 2023 por Ivory Egg
DALI Basics Course  2023DALI Basics Course  2023
DALI Basics Course 2023
Ivory Egg16 vistas
Attacking IoT Devices from a Web Perspective - Linux Day por Simone Onofri
Attacking IoT Devices from a Web Perspective - Linux Day Attacking IoT Devices from a Web Perspective - Linux Day
Attacking IoT Devices from a Web Perspective - Linux Day
Simone Onofri15 vistas
1st parposal presentation.pptx por i238212
1st parposal presentation.pptx1st parposal presentation.pptx
1st parposal presentation.pptx
i2382129 vistas
Five Things You SHOULD Know About Postman por Postman
Five Things You SHOULD Know About PostmanFive Things You SHOULD Know About Postman
Five Things You SHOULD Know About Postman
Postman30 vistas

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
  • 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) }
  • 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