Upload
others
View
9
Download
0
Embed Size (px)
Citation preview
1 / 40
DoIneedtoswitchtoGo(lang)MaxTepkeev20July2016Bilbao,Spain
2 / 40
Aboutme
MaxTepkeevRussia,Moscow
• python-redmine• architect• instructions
https://www.github.com/maxtepkeev
3 / 40
Aboutus
Aidata – online andoffline user datacollection and analysis
1000000000uniqueuserspermonth
http://www.aidata.me
4 / 40
Aboutus
5 / 40
WhyswitchfromPython
• Speed• Concurrency• GIL• No”true”binaries• Dynamictypes
6 / 40
Languagerequirements
• Modern• Fast• Easy• Compiled• Staticallytyped• Supportmainplatforms
7 / 40
WhyGo
StackOverflowquestionsbytag*:
• Go: 16795(1113)• Rust: 4226(429)• D: 2025(34)• Nim: 136(8)
*asof19July2016
8 / 40
Popularity
9 / 40
Go
• CreatedinGoogle• Open-sourcedinNovember2009• Designedbysmartpeople:• RobertGriesemer• RobPike• KenThompson
https://talks.golang.org/2012/splash.article
10 / 40
WhousesGo
• Google• Dropbox• Facebook• IBM• Intel• SpaceX
• Uber• VMware• Yahoo• Twitter• Heroku• DigitalOcean
https://github.com/golang/go/wiki/GoUsers
11 / 40
Projectlayout$GOPATH/
bin/hello#commandexecutableoutyet#commandexecutable
pkg/linux_amd64/github.com/golang/example/stringutil.a#packageobject
src/github.com/golang/example/.git/#Gitrepositorymetadatahello/hello.go#commandsource
outyet/main.go#commandsource
stringutil/reverse.go#packagesource
12 / 40
Packagemanagement$gogetgithub.com/golang/example
src/github.com/golang/example/.git/hello/hello.go
outyet/main.go
stringutil/reverse.go
13 / 40
Packagemanagement• vendoring• gopkg.in• getgb.io
github.com/tools/godepgithub.com/gpmgo/gopmgithub.com/pote/gpmgithub.com/nitrous-io/goopgithub.com/alouche/rodentgithub.com/jingweno/nutgithub.com/niemeyer/gopkggithub.com/mjibson/partygithub.com/kardianos/vendorgithub.com/kisielk/vendorizegithub.com/mattn/gom
github.com/dkulchenko/bunchgithub.com/skelterjohn/wgogithub.com/Masterminds/glidegithub.com/robfig/glockbitbucket.org/vegansk/gobslaunchpad.net/godepsgithub.com/d2fn/gopackgithub.com/laher/gopingithub.com/LyricalSecurity/gigogithub.com/VividCortex/johnny-deps
14 / 40
Commands• gofmt• gotest• gofix• gorun• gorun-race• govet
15 / 40
HelloWorld$GOPATH/src/github.com/user/hello/hello.go:
packagemain
import"fmt"
funcmain(){fmt.Println("Hello,world.")
}
$goinstallgithub.com/user/hello$$GOPATH/bin/helloHello,world.
16 / 40
Comparison:Imports
Go
import"os"
import("os""compress/gzip"
)
importos1"os"
Python
importos
importosimportgzip
importosasos1
17 / 40
Comparison:ImportNames
Go
import"os"
os.Getwd()
Python
importos
os.getcwd()
18 / 40
Comparison:Types
Govar(b bool =trues string ="hey"si int =-1ui uint =1f float32 =1.0c complex64=3il []int =[]int{1, 2}mmap[int]int=map[int]int{1:1}
)
Python
b =Trues ="hey"si =1ui =-1f =1.0c =3jl =[1,2]m ={1:1}
19 / 40
Comparison:Variables
Go
var(i=1j="hey"
)
i:=1j:="hey”
i,j:=1,"hey"
Python
i=1j="hey”
i,j=1,"hey"
20 / 40
Comparison:1st ClassFunctions
Go
funcadd(x,yint)int{returnx+y
}
add:=func(x,yint)int{returnx+y
}
Python
defadd(x,y):returnx+y
add=lambdax,y:x+y
21 / 40
Comparison:Optionalargs
Go
funcsum(nums...int){result:=0for_,num:=rangenums{result+=num
}returnresult
}sum(1,2,3)sum([]int{1,2,3}...)
Python
defsum(*nums):result=0fornuminnums:result+=num
returnresult
sum(1,2,3)sum(*[1,2,3])
22 / 40
Comparison:Optionalkwargs
GotypeKwargsstruct{foo,barstring
}
funcjoin(kwKwargs)string{ifkw.foo==""{kw.foo="foo"}ifkw.bar==""{kw.bar="bar"}returnkw.foo+kw.bar
}
join(Kwargs{})join(Kwargs{bar:"foo"})
Pythondefjoin(foo=None,bar=None):iffooisNone:foo='foo'
ifbarisNone:bar='bar'
returnfoo+bar
join()join(bar='foo')
23 / 40
Comparison:Loops
Go
seq:=[]int{1,2,3}for_,x:=rangeseq{fmt.Println(x)
}
Python
seq=[1,2,3]forx inseq:printx
24 / 40
Comparison:Loops
Go
seq:=[]int{1,2,3}
fori:=0;i<len(seq);i++{fmt.Println(seq[i])
}
Python
seq=[1,2,3]num,count=0,len(seq)
whilenum<count:printseq[num]num+=1
25 / 40
Comparison:Loops
Go
for{fmt.Println("Gorocks")
}
Python
whileTrue:print"Pythonrocks"
26 / 40
Comparison:Comprehensions
Goword:="hello"chars:=[]string{}for_,char:=rangeword{chars=append(chars,string(char))
}fmt.Println(chars)//[hello]
Pythonword="hello"chars=[charforcharinword]printchars#['h','e','l','l','o']
27 / 40
Comparison:Conditionals
Go
ifx:=1;x>0{fmt.Println(x)
}else{fmt.Println("Sorry")
}
Python
x =1ifx>0:printx
else:print"Sorry"
28 / 40
Comparison:Conditionals
Go
switchx:=1;{casex<0:fmt.Println("Negative")
casex>0:fmt.Println("Positive")
default:fmt.Println("Zero")
}
Python
x=1ifx>0:print"Positive"
elifx<0:print"Negative"
else:print"Zero"
29 / 40
Comparison:Slicing
Go
seq:=[]int{1,2,3,4,5}fmt.Print(seq[:2])//[12]fmt.Print(seq[3:]) //[45]fmt.Print(seq[2:3])//[3]
Python
seq=[1,2,3,4,5]printseq[:2] #[1,2]printseq[3:] #[4,5]printseq[2:3] #[3]
30 / 40
Comparison:ErrorHandling
Go
conn,err:=db.Connect()iferr!=nil{fmt.Print("Can'tconnect")
}
panic()/recover()
Python
try:conn=db.Connect()
exceptConnectionError:print"Can'tconnect"
31 / 40
Comparison:Classes
GotypePersonstruct{NamestringAgeint
}
func(pPerson)String()string{returnfmt.Sprintf("%s:%d",p.Name,p.Age)
}
p:=Person{"Batman",45}fmt.Println(p)//Batman:45
PythonclassPerson(object):def__init__(self,name,age):self.name=nameself.age=age
def__str__(self):return"{}:{}".format(self.name,self.age)
p =Person("Batman",45)printp#Batman:45
32 / 40
Comparison:Constructors
GotypePersonstruct{NamestringAgeint
}
funcNewPerson(nstring,aint)*Person{return&Person{Name:n,Age:a}
}
p:=NewPerson("Batman",45)
PythonclassPerson(object):def__init__(self,name,age):self.name=nameself.age=age
p =Person("Batman",45)
33 / 40
Comparison:Inheritance
GotypePersonstruct{Namestring}typeDoctorstruct{Person}
func(pPerson)Eat(){fmt.Println("Eating")
}
func(dDoctor)Heal(){fmt.Println("Healing")
}
d:=Doctor{Person{"GregoryHouse"}}d.Eat() //Eatingd.Heal() //Healing
PythonclassPerson(object):def__init__(self,name):self.name=name
defeat(self):print"Eating"
classDoctor(Person):defheal(self):print"Healing"
d=Doctor("GregoryHouse")d.eat() #"Eating"d.heal()#"Healing"
34 / 40
Comparison:Cleanup
GofuncreadFile()(resultstring){fpath:="/tmp/file"f,err:=os.Open(fpath)iferr!=nil{panic(err)
}deferf.Close()//readingfileherereturnresult
}
Pythondefread_file():result =Nonefpath="/tmp/file"withopen(fpath)asf:result =f.read()
#fileisclosedherereturnresult
35 / 40
Comparison:Concurrent progsGo
urls:=[]string{"http://python.org","http://golang.org"}
responses:=make(chanstring)
for_,url:=rangeurls{gofunc(urlstring){resp,_:=http.Get(url)deferresp.Body.Close()body,_:=ioutil.ReadAll(resp.Body)responses<- string(body)
}(url)}
forresponse:=rangeresponses{fmt.Println(response)
}
Pythonurls=['http://python.org','http://golang.org']
asyncdeffetch(session,url):asyncwithsession.get(url)asresponse:returnawaitresponse.read()
asyncdeffetch_all(session,urls,loop):tasks =[fetch(session,url)forurlinurls]returnawaitasyncio.gather(*tasks)
loop=asyncio.get_event_loop()
withaiohttp.ClientSession(loop=loop)assession:responses=loop.run_until_complete(fetch_all(session,urls,loop))
print(responses)
36 / 40
MoreGofeatures• make()/new()• Arrays• Pointers• Interfaces• Typeassertions• Typeswitches• Bufferedchannels/selectstatement• Unsafepackage• Crosscompilation
37 / 40
PythonfeaturesGolacks• list/dictcomprehensions• generators• decorators• exceptions• metaclasses• descriptors• __magic__methods• set/tuple
38 / 40
Conclusion
Go+ Goodstandardlibrary+ 3rdPartylibsforalmosteverything+ Compiled+ Staticallytyped+ Built-inconcurrency
- Verbose- Nosyntacticsugar- NoSoul
Python+ Goodstandardlibrary+ 3rdPartylibsforeverything+ Lesscode+ Syntacticsugar+ HasSoul
- Interpreted- Dynamicallytyped- Concurrency
39 / 40
GoUsefulLinks1. https://tour.golang.org/2. http://golang.org/doc/effective_go.html3. https://play.golang.org/4. http://golangweekly.com/5. http://devs.cloudimmunity.com/gotchas-
and-common-mistakes-in-go-golang/
40 / 40
Questions
slides:http://slideshare.net/maxtepkeev
github:https://github.com/maxtepkeevemail:[email protected]:max.tepkeevcompany:http://www.aidata.me