Go and the Zen of Python Andrew Gerrand Gopher

What is Go? A new programming language. (First release in November 2009, 1.0 in March 2012.) In a nutshell: A simple language that is easy to learn and read.

Statically typed, but with a dynamic feel.

Compiled to native machine code, but has a fast development cycle.

Language-level concurrency features.

Expansive "batteries included" standard library.

Great tools.

Open source. (BSD) 2

What is Go used for? Go is a general-purpose programming language, like Python, Java, or C. Some common uses: Server daemons

Command-line tools

Web applications

Games

Scientific computing

High frequency trading And, of course, there are many more. Whatever you do, there's a good chance that Go can help you to do it. 3

Who uses Go? Some names that I could fit on one slide: Anchor

BBC World News

Bitly

Canonical

Carbon Games

CloudFlare

Google

Heroku

Iron.io

ngmoco:)

SoundCloud 4

Go one-pagers (1/4) package main import "fmt" func main() { fmt.Println("Hello, Pythonistas!") } 5

Go one-pagers (2/4) package main import ( "fmt" "net/http" ) func main() { http.HandleFunc("/", hello) http.ListenAndServe("localhost:8000", nil) } func hello(w http.ResponseWriter, r *http.Request) { fmt.Fprintln(w, "Hello, Pythonistas!") } 6

Go one-pagers (3/4) package main import ( "fmt"; "net/http"; "time" ) func main() { urls := []string{"http://google.com/", "http://bing.com/"} start := time.Now() done := make(chan string) for _, u := range urls { go func(u string) { resp, err := http.Get(u) if err != nil { done <- u + " " + err.Error() } else { done <- u + " " + resp.Status } }(u) } for _ = range urls { fmt.Println(<-done, time.Since(start)) } } 7

Go one-pagers (4/4) package main import ( "encoding/json"; "fmt"; "io"; "os" ) func main() { d := json.NewDecoder(os.Stdin) var err error for err == nil { var v interface{} if err = d.Decode(&v); err != nil { break } var b []byte if b, err = json.MarshalIndent(v, "", " "); err != nil { break } _, err = os.Stdout.Write(b) } if err != io.EOF { fmt.Fprintln(os.Stderr, err) os.Exit(1) } } 8

Go and me I (adg) joined the Go team at Google in February 2010. Before then, Python had been my day-to-day language for many years. Go has since entirely replaced Python in my life. I am obviously biased, but IMO: if you love Python, you'll love Go. 9

The Zen of Python >>> import this The Zen of Python, by Tim Peters Beautiful is better than ugly. Explicit is better than implicit. Simple is better than complex. Complex is better than complicated. Flat is better than nested. Sparse is better than dense. Readability counts. Special cases aren't special enough to break the rules. Although practicality beats purity. Errors should never pass silently. Unless explicitly silenced. In the face of ambiguity, refuse the temptation to guess. There should be one-- and preferably only one --obvious way to do it. Although that way may not be obvious at first unless you're Dutch. Now is better than never. Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those! 10

Zen is good This is a nice list. I agree with most of it. (Although Python doesn't, sometimes.) 11

Go is Zenlike Go meets nearly all of Tim Peters' criteria. (Maybe not that one about being Dutch.) Let's take a look at some of them and see how Go fits in. 12

"Beautiful is better than ugly." Go has a lightweight, regular syntax reminiscent of C (without the warts). I think it's beautiful. I've certainly seen some beautiful Go code. But beauty, as they say, is in the eye of the beholder. So enough about that. 13

"Simple is better than complex." Methods are just functions (no special location) There's no this or self - the receiver is like any other function argument type Vector struct { X, Y float64 } func (v Vector) Abs() float64 { return math.Sqrt(v.X*v.X + v.Y*v.Y) } 14

"Simple is better than complex." Methods can be declared on any named type (no classes) type Scalar float64 func (s Scalar) Abs() float64 { if s < 0 { return float64(-s) } return float64(s) } 15

"Simple is better than complex." Interfaces are just methods (no data) Interfaces are implicit (no implements declaration) type Abser interface { Abs() float64 } (Both Vector and Scalar implement Abser ,

even though they don't know that Abser exists.) 16

"Simple is better than complex." No constructors or destructors. A constructor is just a function: type Database struct { client *rpc.Client } func NewDatabase(addr string) (*Database, error) { client, err := rpc.Dial("tcp", addr) if err != nil { return nil, err } return &Database{client}, nil } 17

"Simple is better than complex." Identifier case sets visibility. If a name begins with a capital, it is visible outside its package: package foo type Foo struct { // exported type bar int // unexported field } func (f Foo) Bar() {} // exported method func (f Foo) quux() {} // unexported method Only code inside the package can see unexported ("private") names. 18

"Simple is better than complex." Garbage collection (only)

Regular scoping (and name shadowing) rules And there's less: No subtype inheritance* (no subclasses)

No decorators*

No named or optional arguments

No iterators

No generators

No exceptions (*However, Go's "struct embedding" permits similar functionality.) 19

"Explicit is better than implicit." Explicit error handling (no exceptions)

Explicit dependencies

No implicit numeric conversions

Structs define memory layout (no hidden costs) 20

"Flat is better than nested." "Bail early" is idiomatic coding style func badStyle(a int) error { b, err := one(a) if err == nil { c, err := two(b) if err == nil { err = three(c) } } return err } func goodStyle(a int) error { b, err := one(a) if err != nil { return err } c, err := two(b) if err != nil { return err } return three(c) } 21

"Flat is better than nested." Methods are not nested inside classes (no classes, remember?)

Package name space is flat

Multiple files that comprise one package share one name space 22

"Sparse is better than dense." Go's syntax doesn't encourage crazy one-liners. No list comprehensions

No ternary operator ( expression?true:false ) When reading Go code the control flow is obvious. 23

"Practicality beats purity." Go has some built-in generic data structures: maps (dicts)

slices (lists)

channels (a concurrency primitive like Python's queues) 24

"Readability counts." Go was designed for teams of hundreds/thousands of programmers.

Readability is of paramount importance. The gofmt tool enforces "one true style." (No more stupid arguments.) Type inference saves a lot of typing, but not at the cost of readability. Types are still required where they help readability (function declarations, for example). Many other language design decisions were made in the name of readability (case-based name visibility, for example). 25

Bonuses Go's concurrency features will transform the way you think about code: blocking is fine; no need to split concurrent processes into a series of callbacks,

code runs in parallel with little additional cost (no GIL). Deployment is trivial: compile and ship a single statically-linked binary,

goodbye "dependency hell." And there's much more than I could fit into this short talk. :-) 26

"There should be one obvious way to do it." I would argue that this is more true of Go than Python. 27

"Now is better than never." Learn Go today! It's easy. My rule of thumb: productive in one day,

efficient in one week,

expert in one year. References, articles, tutorials, and more: golang.org An interactive web-based tour of Go: tour.golang.org 28