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:

What is Go used for?

Go is a general-purpose programming language, like Python, Java, or C.

Some common uses:

And, of course, there are many more.

Whatever you do, there's a good chance that Go can help you to do it.

Who uses Go?

Some names that I could fit on one slide:

Go one-pagers (1/4)

package main

import "fmt"

func main() {
    fmt.Println("Hello, Pythonistas!")
}

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!")
}

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

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

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.

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!

Zen is good

This is a nice list.

I agree with most of it.

(Although Python doesn't, sometimes.)

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.

"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.

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

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

"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.)

"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
}

"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.

"Simple is better than complex."

And there's less:

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

"Explicit is better than implicit."

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

"Flat is better than nested."

"Sparse is better than dense."

Go's syntax doesn't encourage crazy one-liners.

When reading Go code the control flow is obvious.

"Practicality beats purity."

Go has some built-in generic data structures:

"Readability counts."

Go was designed for teams of hundreds/thousands of programmers.
Readability is of paramount importance.

Bonuses

Go's concurrency features will transform the way you think about code:

Deployment is trivial:

And there's much more than I could fit into this short talk. :-)

"There should be one obvious way to do it."

I would argue that this is more true of Go than Python.

"Now is better than never."

Learn Go today! It's easy.

My rule of thumb:

References, articles, tutorials, and more:

An interactive web-based tour of Go:

Thank you