SlideShare a Scribd company logo
Introduction to Google's Go
Stratio / Datio (May 2016)
Mario Castro
For those who don’t know me…
For those who don’t know me…
Mario Castro
DevOps @ Stratio
Started coding with 13 yo
Java (J++) since 2000
PHP, Python, Java Android, Objective-C, Node.js
Pixar's Certi ed in Renderman's render engine
Other scripting languages (MEL, HScript)
Let's Go
When and who...
History
Design began in late 2007.
Robert Griesemer, Rob Pike, and Ken Thompson.
Ian Lance Taylor and Russ Cox.
Open source since 2009 with a very active community.
Language stable as of Go 1, early 2012.
Who's Go
The men behind it...
Ken Thompson (Ex Bell labs, Unix designer, B programming language)
Rob Pike (Ex Bell labs, Unix Team, Inferno, Plan 9, UTF-8)
Robert Griesemer (V8 Chrome engine, Sawzall)
Why a new language
Why a new language
slow builds
uncontrolled dependencies
poor program understanding (code hard to read, poorly documented...)
Computers are enormously quicker but software development is not faster.
Some fundamental concepts such as garbage collection and parallel computation
are not well supported by popular systems languages.
What's Go (as a programming language)
Statically typed (duck typing)
Compiled language (no more virtual machines... thanks...)
Structure oriented (no inheritance)
Concise and simple syntax, easy to get started with
Good facilities for writing concurrent programs that share state by communicating
Uni ed formatting style for the language
Compilation is fast even with large projects
No need to know a new paradigm or awkward syntax
Comparing Go and Java
Go and Java have much in common
Go and Java have much in common
C family (imperative, braces)
Statically typed
Garbage collected
Methods
Interfaces
Type assertions (instanceof)
Re ection
Classes vs Structs. Interfaces vs... Interfaces?
Go and Java have much in common
This is not a competition
Go is not trying to replace Java
Go has focus on productivity and consolidating Google's experience in large
distributed systems
Google uses Java, Javascript, C++, Python, Go, Sawzal and probably a few other
languages are supported (Je Nelson, inventor of Chrome OS)
Go di ers from Java in several ways
Programs compile to machine code. There's no VM.
Statically linked binaries
Built-in strings (UTF-8)
Built-in generic maps and arrays/slices
Built-in concurrency
Go intentionally leaves out many features
No classes
No constructors
No inheritance
No user-de ned generics
No final, exceptions, annotations...
Go intentionally leaves out many features
Seriously...
No, there are not generics nor algebraic types, monads...
Why does Go leave out those features?
Clarity is critical.
classFoo[F[+_]:Monad,A,B](valexecute:Foo.Request[A]=>F[B],valjoins:Foo.Request[A]=>B=
defbar:Foo[({typel[+a]=WriterT[F,Log[A,B],a]})#l,A,B]={
typeTraceW[FF[+_],+AA]=WriterT[FF,Log[A,B],AA]
defexecute(request:Request[A]):WriterT[F,Log[A,B],B]=
self.execute(request).liftM[TraceW]:++>>(repr=>List(request->request.response(repr,self
When reading code, it should be clear what the program will do.
When writing code, it should be clear how to make the program do what you
want.
Sometimes this means writing out a loop instead of invoking an obscure function.
So, Go is not...
...a functional language
...a new fancy way of coding
...a completely open-source project (no pull-requests)
...a super language that will replace us
...talking about replacement... is not the replacement of Java... or C++... or Cobol...
Why Go
Make programming fast
Safety: type-safe and memory-safe
E cient gargage collector
Reduce typing. No more:
foo.Foo*myFoo=newfoo.Foo(foo.FOO_INIT)
Focus on productivity and concurrency of distributed systems with CSP
concurrency model
CSP Concurrency
CSP Concurrency
Actor model: Entities passing messages to each other that are queued (Erlang,
Scala, Java...)
CSP (Communicating sequential processes) model. Proccesses passing messages
to channels that blocks until the messages are taken but with possibility of using
queues
CSP represents the best known way to write software and organize services together
to form a system. Nature itself provides the best examples; even the human body is a
system of interconnected services — respiratory, cardiovascular, nervous, immune,
etc.
The Tao of Hashicorp https://www.hashicorp.com/blog/tao-of-hashicorp.html(https://www.hashicorp.com/blog/tao-of-hashicorp.html)
This was my face when I read the Tao of Hashicorp...
CSP Concurrency
"Gophers" = processes
Arrows = channels
One "Gopher" could listen to zero or more channels
One "Gopher" can send messages to zero or more channels
CSP Concurrency
Process are anonymous (you can just reach them using a channel)
Channels can be bu ered or unbe ered
Channels can be bi-directional or uni-directional
More than one proccess could be listening the same channel
One process could listen more than one channel
More about this in the workshop
An opinionated language
An opinionated language
Can be weird at the beginning
No brackets in new line (formatter will put them up again)
An Uppercase name means that some method or variable is public, lowercase for
private
Comments of public methods must start with the name of the method
Your project must reside within $GOPATH
Parameters in the de nition of a function must be one character
If you return more than one value, last must be an error
No more than one le with "package main" even if you only have one "main"
function (just works with `go build` but not with `go run [ le]`)
Imports points to some kind of URL that must match a path within your $GOPATH
An opinionated language
Hello World
Hello World
packagemain
funcmain(){
println("HelloWorld!")
} Run
Hello world
Hello web-server
packagemain
import(
"fmt"
"log"
"net/http"
)
funcmain(){
http.HandleFunc("/hello",handleHello)
fmt.Println("servingonhttp://localhost:7777/hello")
log.Fatal(http.ListenAndServe("localhost:7777",nil))
}
funchandleHello(whttp.ResponseWriter,req*http.Request){
fmt.Fprintln(w,"Hello,Stratio")
} Run
More examples: Native Unix piping
funcmain(){
c1:=exec.Command("ls","-lh","/")
c2:=exec.Command("awk","{print$5,"011"$9}")
r1,w1:=io.Pipe()
c1.Stdout=w1
c2.Stdin=r1
c2.Stdout=os.Stdout
c1.Start()
c2.Start()
c1.Wait()
w1.Close()
} Run
Inferred types
No need to write variables types
packagemain
import(
"fmt"
"reflect"
)
funcmain(){
me:="JebediahKerman"
fmt.Println(reflect.TypeOf(me))
} Run
Some common coding features and patterns
More than one object on return (error always at the end)
funcmyFunc()(struct1,struct2,error)
Delegate error pattern
returnnil,err //Errorocurred,delegatetocaller
returno,nil //Noerror
Pointers and references
o:=myObject{} //"o"isanobject
doSomething(&o) //Passingapointer."o"isstillanobject
o:=&myObject{} //Pointertoobject."o"isapointer
funcuseObject(o*myObject) //Areceivedpointer"o"isapointer
Some commong coding features and patterns
Handle every error
iferr!=nil{
log.Fatal(err)
}
Ignore a returned variable (very bad practice, don't trust code that do this)
myobj,_:=myFuncThatReturnsAnObjectAndAnError()
Return anything (quite common in Consul code)
funcmyFunc()interface{}
Do some type assertion
obj:=myFunc()
myString,ok:=obj.(string)
ifok{
println(myString)
}
Testing
Comes with its own test suite
$gotest.
$ok github.com/thehivecorporation/raccoon/parser 0.003s
Getting output...
$gotest-v.
$INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/i-do-not-exist
$INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/wrongJson81990
$INFO[0000]------------------------------>Readingzombiebookfile zombiebook=../examples/example
$INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/no-content6184
$INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/incorrect-keys
$INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/incorrect-keys
$INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/incorrect-keys
$INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/incorrect-keys
$---PASS:TestReadZbookFile(0.00s)
$ zbook_test.go:18:Errorreadingzombiebookfile:open/tmp/i-do-not-exist:nosuchfileordir
$ zbook_test.go:32:ErrorparsingJSON:invalidcharacter'w'lookingforbeginningofobjectke
$PASS
$ok github.com/thehivecorporation/raccoon/parser 0.003s
Testing
Testing
Race condition evaluation integrated
$gotest-race.
$ok github.com/thehivecorporation/raccoon/parser 1.013s
Comes with its own coverage support
$gotest-race-cover.
$ok github.com/thehivecorporation/raccoon/parser 1.011s coverage:68.3%ofstatements
Other tools
gofmt
gofmtformats indentation, spaces, newlines and syntax
Makes most code familiar.
golint
golintwarns you about good practices and suggestions
Example:
typeExecutorinterface{
Execute()
}
linter.go:3:6:exportedtypeExecutorshouldhavecommentorbeunexported
Ok so...
//Interfaceforexecution
typeExecutorinterface{
Execute()
}
linter2.go:3:1:commentonexportedtypeExecutorshouldbeoftheform"Executor..."(withoptiona
//Executoristhestrategypatternfora...
typeExecutorinterface{
Execute()
}
Introduction to Google's Go programming language
golint
golint
If the name always begins the comment, the output of godoc can usefully be run
through grep. Imagine you couldn't remember the name "Compile" but were
looking for the parsing function for regular expressions, so you ran the command,
$godocregexp|grepparse
Compileparsesaregularexpressionandreturns,ifsuccessful,aRegexp
parsed.Itsimplifiessafeinitializationofglobalvariablesholding
cannotbeparsed.Itsimplifiessafeinitializationofglobalvariables
$
Found in "E ective Go"(https://golang.org/doc/e ective_go.html#commentary)
GoDoc
All core packages at your ngertips
You can perform queries in command line
Or open a web server to search
godocindex=true-http=:6060
Search in a speci c package
godocfmt|grep-iread
funcFscanln(rio.Reader,a...interface{})(nint,errerror)
Scanscanstextreadfromstandardinput,storingsuccessive
Scanfscanstextreadfromstandardinput,storingsuccessive
//ReadRunereadsthenextrune(Unicodecodepoint)fromtheinput.
//IfinvokedduringScanln,Fscanln,orSscanln,ReadRune()will
//returnEOFafterreturningthefirst'n'orwhenreadingbeyond
ReadRune()(rrune,sizeint,errerror)
//UnreadRunecausesthenextcalltoReadRunetoreturnthesamerune.
UnreadRune()error
//BecauseReadRuneisimplementedbytheinterface,Readshouldneverbe
//ScanStatemaychoosealwaystoreturnanerrorfromRead.
Read(buf[]byte)(nint,errerror)
Go Get
Useful for dependency management
As simple as
$gogetgithub.com/kubernetes/kubernetes
import"github.com/4ad/doozer"
varclientdoozer.Conn
Most IDE's has an auto-import (on save) features
Work ow
Work ow
Installing Go
From repositories
- Ubuntu users: `sudo apt-get install -y golang`
- Centos/RHEL users: `sudo yum install -y golang`
- Fedora: `sudo dnf install -y golang`
Installing Go
Ok... the slightly harder one: Installing Go
Latest build
golang.org(http://golang.org)
Select your distro
unpack it `tar -zxvf go1.6.2.linux-amd64.tar.gz`
Move the gofolder to your favorite destination (assign permissions according to
destination)
Add a $GOROOT environment variable pointing to your go folder (not the bin
folder within your go folder) to /etc/pro le, ${HOME}/.bashrc, etc.
Add a $GOPATH environment variable pointing to an empty folder that will
represent your global workspace for Go
Add $GOPATH/bin and $GOROOT/bin to your $PATH
The workspace
Workspace is global and it's de ned as an environment variable called $GOPATH.
$exportGOPATH=${HOME}/go
So a `go get github.com/docker/docker` will put the source in
$gogetgithub.com/docker/docker
$cd$GOPATH/src/github.com/docker/docker
Easy, uh?
Our rst Go App
packagemain
funcmain(){
println("Helloworld")
} Run
Our second Go App
packagemain
import"fmt"
funcmain(){
fmt.Printf("(P1)Hello")
goWorld()
}
funcWorld(){
fmt.Printf("world(P2)n")
}
Our third Go App
packagemain
import"fmt"
funcmain(){
fori:=0;i<10000;i++{
gofunc(jint){
fmt.Printf("Proccess#%dn",j)
}(i)
}
varinputstring
fmt.Scanln(&input)
}
Our fourth Go App
funcmain(){
workersCh:=make(chanint,20)
fori:=0;i<20;i++{
goworker(i,workersCh)
}
iter:=0
for{
workersCh<-iter
iter++
time.Sleep(100*time.Millisecond)
}
}
funcworker(idint,wchanint){
for{
select{
casenumber:=<-w:
fmt.Printf("Worker%dgotthenumber%dn",id,number)
time.Sleep(3*time.Second)
}
}
}//END
Our fth Go App
vardelaytime.Duration=5000
funcmain(){
dispatcherCh:=make(chanint,100)
workersCh:=make(chanint)
fori:=0;i<20;i++{
goworker(i,workersCh)
}
godispatcher(dispatcherCh,workersCh)
iter:=0
for{
fmt.Printf("Queuehassize%dn",len(dispatcherCh))
iflen(dispatcherCh)==100{
delay=100
}elseiflen(dispatcherCh)==0{
delay=5000
}
dispatcherCh<-iter
iter++
time.Sleep(100*time.Millisecond)
}
}
funcdispatcher(c,wchanint){
for{
v:=<-c
w<-v
}
}
funcworker(idint,wchanint){
for{
select{
casenumber:=<-w:
fmt.Printf("Worker%dgotthenumber%dn",id,number)
time.Sleep(delay*time.Millisecond)
}
}
}//END
Our sixth...
Contributing in Github
Work ow is slightly di erent
Fork the project into your own github account
Don't clone your fork! Use `go get` of the original git project
As mentioned earlier, it will create a folder within your
$GOPATH/src/[project_owner]/[repo]
Add your fork as a di erente remote (`git remote add my_fork
https://github.com/[my_account]/[my_fork]`)
Work as usual
Push your changes to your fork
Open pull request as usual
(At least, this is how I do it)
Part of Tens
No inheritance
Strongly typed
No “git clone”. Use “go get”
Strongly opinionated
No generics
Has pointers and references
No unused variables nor imports
Strings and structs can’t be nil
You must work always in $GOPATH
No need of locks or semaphores with channels
IDE's and other editing tools
vim + vim-go
emacs + go-model.el
Intellij Idea (has debugging support already. Thanks Abel!)
Atom + go-plus (Has debugging support using Delve plugin)
Sublime Text + GoSublime
Visual Studio Code + vscode-go
LiteIde
Companies using Go
Google
Docker
Net ix
Parse
Digital Ocean
Ebay
AirBnB
Dropbox
Uber
VMWare
Famous software written in Go
Docker
Kubernetes (Google)
Hashicorp's stack (Consul, Terraform, Vault, Serf, Otto, Nomad, Packer)
Prometheus (SoundClound)
CoreOS stack (ETCD, Fleet, Rkt, Flannel)
In uxDB
Grafana
Best resources to learn Go (ordered)
A Tour of Go (interactive tutorial)
https://tour.golang.org/list(https://tour.golang.org/list)
Go By Example
https://gobyexample.com/(https://gobyexample.com/)
How to install Go workspace
https://golang.org/doc/code.html(https://golang.org/doc/code.html)
Go bootcamp (free ebook)
http://www.golangbootcamp.com/(http://www.golangbootcamp.com/)
"E ective Go" Wait a week or two to read
https://golang.org/doc/e ective_go.html(https://golang.org/doc/e ective_go.html)
Other references
Docker and Go: Why we decide to write Docker in Go?
http://www.slideshare.net/jpetazzo/docker-and-go-why-did-we-decide-to-write-
docker-in-go(http://www.slideshare.net/jpetazzo/docker-and-go-why-did-we-decide-to-write-docker-in-go)
By the way
This presentation...
...isalsodonewithaGotool
Questions?
Thank you
Mario Castro
Gopher @ StratioBD(mailto:Gopher%20@%20StratioBD)
@110010111101011(http://twitter.com/110010111101011)
github.com/sayden
mcastro@stratio.com(mailto:mcastro@stratio.com)
Introduction to Google's Go programming language

More Related Content

What's hot (20)

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
 
Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programming
Mahmoud Masih Tehrani
 
Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go
Steven Francia
 
2016 bioinformatics i_python_part_1_wim_vancriekinge
2016 bioinformatics i_python_part_1_wim_vancriekinge2016 bioinformatics i_python_part_1_wim_vancriekinge
2016 bioinformatics i_python_part_1_wim_vancriekinge
Prof. Wim Van Criekinge
 
Go for Rubyists
Go for RubyistsGo for Rubyists
Go for Rubyists
tchandy
 
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
Prof. Wim Van Criekinge
 
Intro to Python for Non-Programmers
Intro to Python for Non-ProgrammersIntro to Python for Non-Programmers
Intro to Python for Non-Programmers
Ahmad Alhour
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
Kostas Saidis
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
Andres Almiray
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developers
Puneet Behl
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
Fariz Darari
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails intro
Miguel Pastor
 
Dynamic Python
Dynamic PythonDynamic Python
Dynamic Python
Chui-Wen Chiu
 
Go Language Hands-on Workshop Material
Go Language Hands-on Workshop MaterialGo Language Hands-on Workshop Material
Go Language Hands-on Workshop Material
Romin Irani
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
Mosky Liu
 
Lisp for Python Programmers
Lisp for Python ProgrammersLisp for Python Programmers
Lisp for Python Programmers
Vsevolod Dyomkin
 
Python basics
Python basicsPython basics
Python basics
RANAALIMAJEEDRAJPUT
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
RajKumar Rampelli
 
Best Python Online Training with Live Project by Expert
Best Python Online Training with Live Project by Expert Best Python Online Training with Live Project by Expert
Best Python Online Training with Live Project by Expert
QA TrainingHub
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
Shivam Gupta
 
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
 
Introduction to go language programming
Introduction to go language programmingIntroduction to go language programming
Introduction to go language programming
Mahmoud Masih Tehrani
 
Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go Painless Data Storage with MongoDB & Go
Painless Data Storage with MongoDB & Go
Steven Francia
 
2016 bioinformatics i_python_part_1_wim_vancriekinge
2016 bioinformatics i_python_part_1_wim_vancriekinge2016 bioinformatics i_python_part_1_wim_vancriekinge
2016 bioinformatics i_python_part_1_wim_vancriekinge
Prof. Wim Van Criekinge
 
Go for Rubyists
Go for RubyistsGo for Rubyists
Go for Rubyists
tchandy
 
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
2016 bioinformatics i_python_part_2_strings_wim_vancriekinge
Prof. Wim Van Criekinge
 
Intro to Python for Non-Programmers
Intro to Python for Non-ProgrammersIntro to Python for Non-Programmers
Intro to Python for Non-Programmers
Ahmad Alhour
 
An Introduction to Groovy for Java Developers
An Introduction to Groovy for Java DevelopersAn Introduction to Groovy for Java Developers
An Introduction to Groovy for Java Developers
Kostas Saidis
 
Groovy for Java Developers
Groovy for Java DevelopersGroovy for Java Developers
Groovy for Java Developers
Andres Almiray
 
Groovy for java developers
Groovy for java developersGroovy for java developers
Groovy for java developers
Puneet Behl
 
Python in 30 minutes!
Python in 30 minutes!Python in 30 minutes!
Python in 30 minutes!
Fariz Darari
 
Groovy and Grails intro
Groovy and Grails introGroovy and Grails intro
Groovy and Grails intro
Miguel Pastor
 
Go Language Hands-on Workshop Material
Go Language Hands-on Workshop MaterialGo Language Hands-on Workshop Material
Go Language Hands-on Workshop Material
Romin Irani
 
Programming with Python - Basic
Programming with Python - BasicProgramming with Python - Basic
Programming with Python - Basic
Mosky Liu
 
Lisp for Python Programmers
Lisp for Python ProgrammersLisp for Python Programmers
Lisp for Python Programmers
Vsevolod Dyomkin
 
Learn python – for beginners
Learn python – for beginnersLearn python – for beginners
Learn python – for beginners
RajKumar Rampelli
 
Best Python Online Training with Live Project by Expert
Best Python Online Training with Live Project by Expert Best Python Online Training with Live Project by Expert
Best Python Online Training with Live Project by Expert
QA TrainingHub
 
Python Seminar PPT
Python Seminar PPTPython Seminar PPT
Python Seminar PPT
Shivam Gupta
 

Similar to Introduction to Google's Go programming language (20)

Ready, set, go! An introduction to the Go programming language
Ready, set, go! An introduction to the Go programming languageReady, set, go! An introduction to the Go programming language
Ready, set, go! An introduction to the Go programming language
RTigger
 
Go. why it goes v2
Go. why it goes v2Go. why it goes v2
Go. why it goes v2
Sergey Pichkurov
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golang
Yoni Davidson
 
A First Look at Google's Go Programming Language
A First Look at Google's Go Programming LanguageA First Look at Google's Go Programming Language
A First Look at Google's Go Programming Language
Ganesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
Ganesh Samarthyam
 
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
Dvir Volk
 
Go. Why it goes
Go. Why it goesGo. Why it goes
Go. Why it goes
Sergey Pichkurov
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
Simon Hewitt
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
Amal Mohan N
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
Aniruddha Chakrabarti
 
Introduction to Programming in Go
Introduction to Programming in GoIntroduction to Programming in Go
Introduction to Programming in Go
Amr Hassan
 
An Introduction to Go
An Introduction to GoAn Introduction to Go
An Introduction to Go
Imesh Gunaratne
 
Go fundamentals
Go fundamentalsGo fundamentals
Go fundamentals
Ron Barabash
 
Ready to go
Ready to goReady to go
Ready to go
Atin Mukherjee
 
Introduction to Go programming
Introduction to Go programmingIntroduction to Go programming
Introduction to Go programming
Exotel
 
Go lang
Go langGo lang
Go lang
Suelen Carvalho
 
Golang workshop - Mindbowser
Golang workshop - MindbowserGolang workshop - Mindbowser
Golang workshop - Mindbowser
Mindbowser Inc
 
Go: What's Different ?
Go: What's Different ?Go: What's Different ?
Go: What's Different ?
Tarun Vashisth
 
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
I.I.S. G. Vallauri - Fossano
 
Introduction to go, and why it's awesome
Introduction to go, and why it's awesomeIntroduction to go, and why it's awesome
Introduction to go, and why it's awesome
Janet Kuo
 
Ready, set, go! An introduction to the Go programming language
Ready, set, go! An introduction to the Go programming languageReady, set, go! An introduction to the Go programming language
Ready, set, go! An introduction to the Go programming language
RTigger
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golang
Yoni Davidson
 
A First Look at Google's Go Programming Language
A First Look at Google's Go Programming LanguageA First Look at Google's Go Programming Language
A First Look at Google's Go Programming Language
Ganesh Samarthyam
 
Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction Google's Go Programming Language - Introduction
Google's Go Programming Language - Introduction
Ganesh Samarthyam
 
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
Dvir Volk
 
Introduction to Go
Introduction to GoIntroduction to Go
Introduction to Go
Simon Hewitt
 
Introduction to go lang
Introduction to go langIntroduction to go lang
Introduction to go lang
Amal Mohan N
 
Golang - Overview of Go (golang) Language
Golang - Overview of Go (golang) LanguageGolang - Overview of Go (golang) Language
Golang - Overview of Go (golang) Language
Aniruddha Chakrabarti
 
Introduction to Programming in Go
Introduction to Programming in GoIntroduction to Programming in Go
Introduction to Programming in Go
Amr Hassan
 
Introduction to Go programming
Introduction to Go programmingIntroduction to Go programming
Introduction to Go programming
Exotel
 
Golang workshop - Mindbowser
Golang workshop - MindbowserGolang workshop - Mindbowser
Golang workshop - Mindbowser
Mindbowser Inc
 
Go: What's Different ?
Go: What's Different ?Go: What's Different ?
Go: What's Different ?
Tarun Vashisth
 
Introduction to go, and why it's awesome
Introduction to go, and why it's awesomeIntroduction to go, and why it's awesome
Introduction to go, and why it's awesome
Janet Kuo
 
Ad

Recently uploaded (20)

Structure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS pptStructure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS ppt
Wahajch
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
A Comprehensive Investigation into the Accuracy of Soft Computing Tools for D...
Journal of Soft Computing in Civil Engineering
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Structure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS pptStructure of OS ppt Structure of OsS ppt
Structure of OS ppt Structure of OsS ppt
Wahajch
 
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptxWeek 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
Week 6- PC HARDWARE AND MAINTENANCE-THEORY.pptx
dayananda54
 
Pavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible PavementsPavement and its types, Application of rigid and Flexible Pavements
Pavement and its types, Application of rigid and Flexible Pavements
Sakthivel M
 
Research_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptxResearch_Sensitization_&_Innovative_Project_Development.pptx
Research_Sensitization_&_Innovative_Project_Development.pptx
niranjancse
 
Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.Third Review PPT that consists of the project d etails like abstract.
Third Review PPT that consists of the project d etails like abstract.
Sowndarya6
 
ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025ACEP Magazine Fifth Edition on 5june2025
ACEP Magazine Fifth Edition on 5june2025
Rahul
 
Flow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docxFlow Chart Proses Bisnis prosscesss.docx
Flow Chart Proses Bisnis prosscesss.docx
rifka575530
 
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) ProjectMontreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Montreal Dreamin' 25 - Introduction to the MuleSoft AI Chain (MAC) Project
Alexandra N. Martinez
 
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
362 Alec Data Center Solutions-Slysium Data Center-AUH-ABB Furse.pdf
djiceramil
 
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbbTree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
Tree_Traversals.pptbbbbbbbbbbbbbbbbbbbbbbbbb
RATNANITINPATIL
 
Airport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptxAirport_Substation_With_Diagrams (2).pptx
Airport_Substation_With_Diagrams (2).pptx
BibekMedhi2
 
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdfIrja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus - Beyond Pass and Fail - DevTalks.pdf
Irja Straus
 
operationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagementoperationg systemsdocumentmemorymanagement
operationg systemsdocumentmemorymanagement
SNIGDHAAPPANABHOTLA
 
Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401Universal Human Values and professional ethics Quantum AKTU BVE401
Universal Human Values and professional ethics Quantum AKTU BVE401
Unknown
 
Présentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptxPrésentation_gestion[1] [Autosaved].pptx
Présentation_gestion[1] [Autosaved].pptx
KHADIJAESSAKET
 
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptxDevelopment of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
Development of Portable Biomass Briquetting Machine (S, A & D)-1.pptx
aniket862935
 
David Boutry - Mentors Junior Developers
David Boutry - Mentors Junior DevelopersDavid Boutry - Mentors Junior Developers
David Boutry - Mentors Junior Developers
David Boutry
 
Introduction to AI agent development with MCP
Introduction to AI agent development with MCPIntroduction to AI agent development with MCP
Introduction to AI agent development with MCP
Dori Waldman
 
New Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docxNew Microsoft Office Word Documentfrf.docx
New Microsoft Office Word Documentfrf.docx
misheetasah
 
Ad

Introduction to Google's Go programming language

  • 1. Introduction to Google's Go Stratio / Datio (May 2016) Mario Castro
  • 2. For those who don’t know me…
  • 3. For those who don’t know me… Mario Castro DevOps @ Stratio Started coding with 13 yo Java (J++) since 2000 PHP, Python, Java Android, Objective-C, Node.js Pixar's Certi ed in Renderman's render engine Other scripting languages (MEL, HScript)
  • 6. History Design began in late 2007. Robert Griesemer, Rob Pike, and Ken Thompson. Ian Lance Taylor and Russ Cox. Open source since 2009 with a very active community. Language stable as of Go 1, early 2012.
  • 7. Who's Go The men behind it... Ken Thompson (Ex Bell labs, Unix designer, B programming language) Rob Pike (Ex Bell labs, Unix Team, Inferno, Plan 9, UTF-8) Robert Griesemer (V8 Chrome engine, Sawzall)
  • 8. Why a new language
  • 9. Why a new language slow builds uncontrolled dependencies poor program understanding (code hard to read, poorly documented...) Computers are enormously quicker but software development is not faster. Some fundamental concepts such as garbage collection and parallel computation are not well supported by popular systems languages.
  • 10. What's Go (as a programming language) Statically typed (duck typing) Compiled language (no more virtual machines... thanks...) Structure oriented (no inheritance) Concise and simple syntax, easy to get started with Good facilities for writing concurrent programs that share state by communicating Uni ed formatting style for the language Compilation is fast even with large projects No need to know a new paradigm or awkward syntax
  • 12. Go and Java have much in common
  • 13. Go and Java have much in common C family (imperative, braces) Statically typed Garbage collected Methods Interfaces Type assertions (instanceof) Re ection
  • 14. Classes vs Structs. Interfaces vs... Interfaces?
  • 15. Go and Java have much in common
  • 16. This is not a competition Go is not trying to replace Java Go has focus on productivity and consolidating Google's experience in large distributed systems Google uses Java, Javascript, C++, Python, Go, Sawzal and probably a few other languages are supported (Je Nelson, inventor of Chrome OS)
  • 17. Go di ers from Java in several ways Programs compile to machine code. There's no VM. Statically linked binaries Built-in strings (UTF-8) Built-in generic maps and arrays/slices Built-in concurrency
  • 18. Go intentionally leaves out many features No classes No constructors No inheritance No user-de ned generics No final, exceptions, annotations...
  • 19. Go intentionally leaves out many features
  • 20. Seriously... No, there are not generics nor algebraic types, monads...
  • 21. Why does Go leave out those features? Clarity is critical. classFoo[F[+_]:Monad,A,B](valexecute:Foo.Request[A]=>F[B],valjoins:Foo.Request[A]=>B= defbar:Foo[({typel[+a]=WriterT[F,Log[A,B],a]})#l,A,B]={ typeTraceW[FF[+_],+AA]=WriterT[FF,Log[A,B],AA] defexecute(request:Request[A]):WriterT[F,Log[A,B],B]= self.execute(request).liftM[TraceW]:++>>(repr=>List(request->request.response(repr,self When reading code, it should be clear what the program will do. When writing code, it should be clear how to make the program do what you want. Sometimes this means writing out a loop instead of invoking an obscure function.
  • 22. So, Go is not... ...a functional language ...a new fancy way of coding ...a completely open-source project (no pull-requests) ...a super language that will replace us ...talking about replacement... is not the replacement of Java... or C++... or Cobol...
  • 23. Why Go Make programming fast Safety: type-safe and memory-safe E cient gargage collector Reduce typing. No more: foo.Foo*myFoo=newfoo.Foo(foo.FOO_INIT) Focus on productivity and concurrency of distributed systems with CSP concurrency model
  • 25. CSP Concurrency Actor model: Entities passing messages to each other that are queued (Erlang, Scala, Java...) CSP (Communicating sequential processes) model. Proccesses passing messages to channels that blocks until the messages are taken but with possibility of using queues CSP represents the best known way to write software and organize services together to form a system. Nature itself provides the best examples; even the human body is a system of interconnected services — respiratory, cardiovascular, nervous, immune, etc. The Tao of Hashicorp https://www.hashicorp.com/blog/tao-of-hashicorp.html(https://www.hashicorp.com/blog/tao-of-hashicorp.html) This was my face when I read the Tao of Hashicorp...
  • 26. CSP Concurrency "Gophers" = processes Arrows = channels One "Gopher" could listen to zero or more channels One "Gopher" can send messages to zero or more channels
  • 27. CSP Concurrency Process are anonymous (you can just reach them using a channel) Channels can be bu ered or unbe ered Channels can be bi-directional or uni-directional More than one proccess could be listening the same channel One process could listen more than one channel More about this in the workshop
  • 29. An opinionated language Can be weird at the beginning No brackets in new line (formatter will put them up again) An Uppercase name means that some method or variable is public, lowercase for private Comments of public methods must start with the name of the method Your project must reside within $GOPATH Parameters in the de nition of a function must be one character If you return more than one value, last must be an error No more than one le with "package main" even if you only have one "main" function (just works with `go build` but not with `go run [ le]`) Imports points to some kind of URL that must match a path within your $GOPATH
  • 35. More examples: Native Unix piping funcmain(){ c1:=exec.Command("ls","-lh","/") c2:=exec.Command("awk","{print$5,"011"$9}") r1,w1:=io.Pipe() c1.Stdout=w1 c2.Stdin=r1 c2.Stdout=os.Stdout c1.Start() c2.Start() c1.Wait() w1.Close() } Run
  • 36. Inferred types No need to write variables types packagemain import( "fmt" "reflect" ) funcmain(){ me:="JebediahKerman" fmt.Println(reflect.TypeOf(me)) } Run
  • 37. Some common coding features and patterns More than one object on return (error always at the end) funcmyFunc()(struct1,struct2,error) Delegate error pattern returnnil,err //Errorocurred,delegatetocaller returno,nil //Noerror Pointers and references o:=myObject{} //"o"isanobject doSomething(&o) //Passingapointer."o"isstillanobject o:=&myObject{} //Pointertoobject."o"isapointer funcuseObject(o*myObject) //Areceivedpointer"o"isapointer
  • 38. Some commong coding features and patterns Handle every error iferr!=nil{ log.Fatal(err) } Ignore a returned variable (very bad practice, don't trust code that do this) myobj,_:=myFuncThatReturnsAnObjectAndAnError() Return anything (quite common in Consul code) funcmyFunc()interface{} Do some type assertion obj:=myFunc() myString,ok:=obj.(string) ifok{ println(myString) }
  • 39. Testing Comes with its own test suite $gotest. $ok github.com/thehivecorporation/raccoon/parser 0.003s Getting output... $gotest-v. $INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/i-do-not-exist $INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/wrongJson81990 $INFO[0000]------------------------------>Readingzombiebookfile zombiebook=../examples/example $INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/no-content6184 $INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/incorrect-keys $INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/incorrect-keys $INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/incorrect-keys $INFO[0000]------------------------------>Readingzombiebookfile zombiebook=/tmp/incorrect-keys $---PASS:TestReadZbookFile(0.00s) $ zbook_test.go:18:Errorreadingzombiebookfile:open/tmp/i-do-not-exist:nosuchfileordir $ zbook_test.go:32:ErrorparsingJSON:invalidcharacter'w'lookingforbeginningofobjectke $PASS $ok github.com/thehivecorporation/raccoon/parser 0.003s
  • 41. Testing Race condition evaluation integrated $gotest-race. $ok github.com/thehivecorporation/raccoon/parser 1.013s Comes with its own coverage support $gotest-race-cover. $ok github.com/thehivecorporation/raccoon/parser 1.011s coverage:68.3%ofstatements
  • 43. gofmt gofmtformats indentation, spaces, newlines and syntax Makes most code familiar.
  • 44. golint golintwarns you about good practices and suggestions Example: typeExecutorinterface{ Execute() } linter.go:3:6:exportedtypeExecutorshouldhavecommentorbeunexported Ok so... //Interfaceforexecution typeExecutorinterface{ Execute() } linter2.go:3:1:commentonexportedtypeExecutorshouldbeoftheform"Executor..."(withoptiona //Executoristhestrategypatternfora... typeExecutorinterface{ Execute() }
  • 47. golint If the name always begins the comment, the output of godoc can usefully be run through grep. Imagine you couldn't remember the name "Compile" but were looking for the parsing function for regular expressions, so you ran the command, $godocregexp|grepparse Compileparsesaregularexpressionandreturns,ifsuccessful,aRegexp parsed.Itsimplifiessafeinitializationofglobalvariablesholding cannotbeparsed.Itsimplifiessafeinitializationofglobalvariables $ Found in "E ective Go"(https://golang.org/doc/e ective_go.html#commentary)
  • 48. GoDoc All core packages at your ngertips You can perform queries in command line Or open a web server to search godocindex=true-http=:6060 Search in a speci c package godocfmt|grep-iread funcFscanln(rio.Reader,a...interface{})(nint,errerror) Scanscanstextreadfromstandardinput,storingsuccessive Scanfscanstextreadfromstandardinput,storingsuccessive //ReadRunereadsthenextrune(Unicodecodepoint)fromtheinput. //IfinvokedduringScanln,Fscanln,orSscanln,ReadRune()will //returnEOFafterreturningthefirst'n'orwhenreadingbeyond ReadRune()(rrune,sizeint,errerror) //UnreadRunecausesthenextcalltoReadRunetoreturnthesamerune. UnreadRune()error //BecauseReadRuneisimplementedbytheinterface,Readshouldneverbe //ScanStatemaychoosealwaystoreturnanerrorfromRead. Read(buf[]byte)(nint,errerror)
  • 49. Go Get Useful for dependency management As simple as $gogetgithub.com/kubernetes/kubernetes import"github.com/4ad/doozer" varclientdoozer.Conn Most IDE's has an auto-import (on save) features
  • 52. Installing Go From repositories - Ubuntu users: `sudo apt-get install -y golang` - Centos/RHEL users: `sudo yum install -y golang` - Fedora: `sudo dnf install -y golang`
  • 54. Ok... the slightly harder one: Installing Go Latest build golang.org(http://golang.org) Select your distro unpack it `tar -zxvf go1.6.2.linux-amd64.tar.gz` Move the gofolder to your favorite destination (assign permissions according to destination) Add a $GOROOT environment variable pointing to your go folder (not the bin folder within your go folder) to /etc/pro le, ${HOME}/.bashrc, etc. Add a $GOPATH environment variable pointing to an empty folder that will represent your global workspace for Go Add $GOPATH/bin and $GOROOT/bin to your $PATH
  • 55. The workspace Workspace is global and it's de ned as an environment variable called $GOPATH. $exportGOPATH=${HOME}/go So a `go get github.com/docker/docker` will put the source in $gogetgithub.com/docker/docker $cd$GOPATH/src/github.com/docker/docker Easy, uh?
  • 56. Our rst Go App packagemain funcmain(){ println("Helloworld") } Run
  • 57. Our second Go App packagemain import"fmt" funcmain(){ fmt.Printf("(P1)Hello") goWorld() } funcWorld(){ fmt.Printf("world(P2)n") }
  • 58. Our third Go App packagemain import"fmt" funcmain(){ fori:=0;i<10000;i++{ gofunc(jint){ fmt.Printf("Proccess#%dn",j) }(i) } varinputstring fmt.Scanln(&input) }
  • 59. Our fourth Go App funcmain(){ workersCh:=make(chanint,20) fori:=0;i<20;i++{ goworker(i,workersCh) } iter:=0 for{ workersCh<-iter iter++ time.Sleep(100*time.Millisecond) } } funcworker(idint,wchanint){ for{ select{ casenumber:=<-w: fmt.Printf("Worker%dgotthenumber%dn",id,number) time.Sleep(3*time.Second) } } }//END
  • 60. Our fth Go App vardelaytime.Duration=5000 funcmain(){ dispatcherCh:=make(chanint,100) workersCh:=make(chanint) fori:=0;i<20;i++{ goworker(i,workersCh) } godispatcher(dispatcherCh,workersCh) iter:=0 for{ fmt.Printf("Queuehassize%dn",len(dispatcherCh)) iflen(dispatcherCh)==100{ delay=100 }elseiflen(dispatcherCh)==0{ delay=5000 } dispatcherCh<-iter iter++ time.Sleep(100*time.Millisecond) } }
  • 63. Contributing in Github Work ow is slightly di erent Fork the project into your own github account Don't clone your fork! Use `go get` of the original git project As mentioned earlier, it will create a folder within your $GOPATH/src/[project_owner]/[repo] Add your fork as a di erente remote (`git remote add my_fork https://github.com/[my_account]/[my_fork]`) Work as usual Push your changes to your fork Open pull request as usual (At least, this is how I do it)
  • 64. Part of Tens No inheritance Strongly typed No “git clone”. Use “go get” Strongly opinionated No generics Has pointers and references No unused variables nor imports Strings and structs can’t be nil You must work always in $GOPATH No need of locks or semaphores with channels
  • 65. IDE's and other editing tools vim + vim-go emacs + go-model.el Intellij Idea (has debugging support already. Thanks Abel!) Atom + go-plus (Has debugging support using Delve plugin) Sublime Text + GoSublime Visual Studio Code + vscode-go LiteIde
  • 66. Companies using Go Google Docker Net ix Parse Digital Ocean Ebay AirBnB Dropbox Uber VMWare
  • 67. Famous software written in Go Docker Kubernetes (Google) Hashicorp's stack (Consul, Terraform, Vault, Serf, Otto, Nomad, Packer) Prometheus (SoundClound) CoreOS stack (ETCD, Fleet, Rkt, Flannel) In uxDB Grafana
  • 68. Best resources to learn Go (ordered) A Tour of Go (interactive tutorial) https://tour.golang.org/list(https://tour.golang.org/list) Go By Example https://gobyexample.com/(https://gobyexample.com/) How to install Go workspace https://golang.org/doc/code.html(https://golang.org/doc/code.html) Go bootcamp (free ebook) http://www.golangbootcamp.com/(http://www.golangbootcamp.com/) "E ective Go" Wait a week or two to read https://golang.org/doc/e ective_go.html(https://golang.org/doc/e ective_go.html)
  • 69. Other references Docker and Go: Why we decide to write Docker in Go? http://www.slideshare.net/jpetazzo/docker-and-go-why-did-we-decide-to-write- docker-in-go(http://www.slideshare.net/jpetazzo/docker-and-go-why-did-we-decide-to-write-docker-in-go)
  • 73. Thank you Mario Castro Gopher @ StratioBD(mailto:Gopher%20@%20StratioBD) @110010111101011(http://twitter.com/110010111101011) github.com/sayden [email protected](mailto:[email protected])