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:

2

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.

3

Who uses Go?

Some names that I could fit on one slide:

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

And there's less:

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

19

"Explicit is better than implicit."

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

22

"Sparse is better than dense."

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

When reading Go code the control flow is obvious.

23

"Practicality beats purity."

Go has some built-in generic data structures:

24

"Readability counts."

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

25

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

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:

References, articles, tutorials, and more:

An interactive web-based tour of Go:

28

Thank you

Use the left and right arrow keys or click the left and right edges of the page to navigate between slides.
(Press 'H' or navigate to hide this message.)