do i need to switch to go lang
play

Do I need to switch to Go(lang) Max Tepkeev 20 July 2016 Bilbao, - PowerPoint PPT Presentation

Do I need to switch to Go(lang) Max Tepkeev 20 July 2016 Bilbao, Spain 1 / 40 About me Max Tepkeev Russia, Moscow python-redmine architect instructions https://www.github.com/maxtepkeev 2 / 40 About us Aidata online


  1. Do I need to switch to Go(lang) Max Tepkeev 20 July 2016 Bilbao, Spain 1 / 40

  2. About me Max Tepkeev Russia, Moscow • python-redmine • architect • instructions https://www.github.com/maxtepkeev 2 / 40

  3. About us Aidata – online and offline user data collection and analysis 1 000 000 000 unique users per month http://www.aidata.me 3 / 40

  4. About us 4 / 40

  5. Why switch from Python Speed • Concurrency • GIL • No ”true” binaries • Dynamic types • 5 / 40

  6. Language requirements • Modern • Fast • Easy • Compiled • Statically typed • Support main platforms 6 / 40

  7. Why Go StackOverflow questions by tag * : • Go: 16795 (1113) • Rust: 4226 (429) • D: 2025 (34) • Nim: 136 (8) * as of 19 July 2016 7 / 40

  8. Popularity 8 / 40

  9. Go • Created in Google • Open-sourced in November 2009 • Designed by smart people: • Robert Griesemer • Rob Pike • Ken Thompson https://talks.golang.org/2012/splash.article 9 / 40

  10. Who uses Go Google Uber • • Dropbox VMware • • Facebook Yahoo • • IBM Twitter • • Intel Heroku • • SpaceX DigitalOcean • • https://github.com/golang/go/wiki/GoUsers 10 / 40

  11. Project layout $GOPATH/ bin/ hello # command executable outyet # command executable pkg/ linux_amd64/ github.com/golang/example/ stringutil.a # package object src/ github.com/golang/example/ .git/ # Git repository metadata hello/ hello.go # command source outyet/ main.go # command source stringutil/ reverse.go # package source 11 / 40

  12. Package management $ go get github.com/golang/example src/ github.com/golang/example/ .git/ hello/ hello.go outyet/ main.go stringutil/ reverse.go 12 / 40

  13. Package management • vendoring • gopkg.in • getgb.io github.com/dkulchenko/bunch github.com/tools/godep github.com/skelterjohn/wgo github.com/gpmgo/gopm github.com/Masterminds/glide github.com/pote/gpm github.com/robfig/glock github.com/nitrous-io/goop bitbucket.org/vegansk/gobs github.com/alouche/rodent launchpad.net/godeps github.com/jingweno/nut github.com/d2fn/gopack github.com/niemeyer/gopkg github.com/laher/gopin github.com/mjibson/party github.com/LyricalSecurity/gigo github.com/kardianos/vendor github.com/VividCortex/johnny-deps github.com/kisielk/vendorize github.com/mattn/gom 13 / 40

  14. Commands • go fmt • go test • go fix • go run • go run -race • go vet 14 / 40

  15. Hello World $GOPATH/src/github.com/user/hello/hello.go: package main import "fmt" func main() { fmt.Println( "Hello, world." ) } $ go install github.com/user/hello $ $GOPATH/bin/hello Hello, world. 15 / 40

  16. Comparison: Imports Python Go import os import "os" import os import ( import gzip "os" "compress/gzip" ) import os as os1 import os1 "os" 16 / 40

  17. Comparison: Import Names Python Go import os import "os" os.getcwd() os.Getwd() 17 / 40

  18. Comparison: Types Python Go var ( b = True b bool = true s = "hey" s string = "hey" si = 1 si int = -1 ui = -1 ui uint = 1 f = 1.0 f float32 = 1.0 c = 3j c complex64 = 3i l = [1, 2] l []int = []int{1, 2} m = {1:1} m map [int]int = map [int]int{1: 1} ) 18 / 40

  19. Comparison: Variables Python Go i = 1 var ( j = "hey” i = 1 j = "hey" ) i := 1 j := "hey” i, j = 1, "hey" i, j := 1, "hey" 19 / 40

  20. Comparison: 1 st Class Functions Python Go def add(x, y): func add(x, y int) int { return x + y return x + y } add = lambda x, y: x + y add := func (x, y int) int { return x + y } 20 / 40

  21. Comparison: Optional args Python Go def sum(*nums): func sum(nums ...int) { result = 0 result := 0 for num in nums: for _, num := range nums { result += num result += num return result } return result } sum(1, 2, 3) sum(1, 2, 3) sum(*[1, 2, 3]) sum([]int{1, 2, 3}...) 21 / 40

  22. Comparison: Optional kwargs Python Go def join(foo=None, bar=None): type Kwargs struct { if foo is None: foo, bar string foo = 'foo' } if bar is None: func join(kw Kwargs) string { bar = 'bar' if kw.foo == "" {kw.foo = "foo" } return foo + bar if kw.bar == "" {kw.bar = "bar" } return kw.foo + kw.bar } join() join(Kwargs{}) join(bar= 'foo' ) join(Kwargs{bar: "foo" }) 22 / 40

  23. Comparison: Loops Python Go seq = [1, 2, 3] seq := []int{1, 2, 3} for x in seq: for _, x := range seq { print x fmt.Println(x) } 23 / 40

  24. Comparison: Loops Python Go seq = [1, 2, 3] seq := []int{1, 2, 3} num, count = 0, len(seq) while num < count: for i := 0; i < len(seq); i++ { print seq[num] fmt.Println(seq[i]) num += 1 } 24 / 40

  25. Comparison: Loops Python Go while True: for { print "Python rocks" fmt.Println( "Go rocks" ) } 25 / 40

  26. Comparison: Comprehensions Python Go word = "hello" word := "hello" chars = [char for char in word] chars := []string{} print chars # ['h', 'e', 'l', 'l', 'o'] for _, char := range word { chars = append(chars, string(char)) } fmt.Println(chars) // [h e l l o] 26 / 40

  27. Comparison: Conditionals Python Go x = 1 if x := 1; x > 0 { if x > 0: fmt.Println(x) print x } else { else : fmt.Println( "Sorry" ) print "Sorry" } 27 / 40

  28. Comparison: Conditionals Python Go x = 1 switch x := 1; { if x > 0: case x < 0: print "Positive" fmt.Println( "Negative" ) elif x < 0: case x > 0: print "Negative" fmt.Println( "Positive" ) else : default : print "Zero" fmt.Println( "Zero" ) } 28 / 40

  29. Comparison: Slicing Python Go seq = [1, 2, 3, 4, 5] seq := []int{1, 2, 3, 4, 5} print seq[:2] # [1, 2] fmt.Print(seq[:2]) // [1 2] print seq[3:] # [4, 5] fmt.Print(seq[3:]) // [4 5] print seq[2:3] # [3] fmt.Print(seq[2:3]) // [3] 29 / 40

  30. Comparison: Error Handling Python Go try : conn, err := db.Connect() conn = db.Connect() if err != nil { except ConnectionError: fmt.Print( "Can't connect" ) print "Can't connect" } panic() / recover() 30 / 40

  31. Comparison: Classes Python Go class Person(object): type Person struct { def __init__(self, name, age): Name string self.name = name Age int self.age = age } def __str__(self): func (p Person) String() string { return "{}: {}" .format( return fmt.Sprintf( self.name, self.age) "%s: %d" , p.Name, p.Age) } p = Person( "Batman" , 45) p := Person{ "Batman" , 45} print p # Batman: 45 fmt.Println(p) // Batman: 45 31 / 40

  32. Comparison: Constructors Python Go class Person(object): type Person struct { def __init__(self, name, age): Name string self.name = name Age int self.age = age } func NewPerson(n string, a int) *Person { return &Person{Name: n, Age: a} } p = Person( "Batman" , 45) p := NewPerson( "Batman" , 45) 32 / 40

  33. Comparison: Inheritance Python Go class Person(object): type Person struct { Name string } def __init__(self, name): type Doctor struct { Person } self.name = name func (p Person) Eat() { def eat(self): fmt.Println( "Eating" ) print "Eating" } class Doctor(Person): func (d Doctor) Heal() { def heal(self): fmt.Println( "Healing" ) print "Healing" } d := Doctor{Person{ "Gregory House" }} d = Doctor( "Gregory House" ) d.Eat() // Eating d.eat() # "Eating" d.Heal() // Healing d.heal() # "Healing" 33 / 40

  34. Comparison: Cleanup Python Go def read_file(): func readFile() (result string) { result = None fpath := "/tmp/file" fpath = "/tmp/file" f, err := os.Open(fpath) with open(fpath) as f: if err != nil { result = f.read() panic(err) # file is closed here } return result defer f.Close() // reading file here return result } 34 / 40

  35. Comparison: Concurrent progs Python Go urls = [ 'http://python.org' , 'http://golang.org' ] urls := []string{ "http://python.org" , "http://golang.org" } async def fetch(session, url): async with session.get(url) as response: responses := make( chan string) return await response.read() for _, url := range urls { async def fetch_all(session, urls, loop): go func (url string) { tasks = [fetch(session, url) for url in urls] resp, _ := http.Get(url) return await asyncio.gather(*tasks) defer resp.Body.Close() body, _ := ioutil.ReadAll(resp.Body) loop = asyncio.get_event_loop() responses <- string(body) }(url) with aiohttp.ClientSession(loop=loop) as session: } responses = loop.run_until_complete( fetch_all(session, urls, loop)) for response := range responses { fmt.Println(response) print (responses) } 35 / 40

  36. More Go features • make() / new() • Arrays • Pointers • Interfaces • Type assertions • Type switches • Buffered channels / select statement • Unsafe package • Cross compilation 36 / 40

  37. Python features Go lacks • list / dict comprehensions • generators • decorators • exceptions • metaclasses • descriptors • __magic__ methods • set / tuple 37 / 40

Recommend


More recommend