Lesson 27. Much ado about nil

 

After reading lesson 27, you’ll be able to

  • Do something with nothing
  • Understand the trouble with nil
  • See how Go improves on nil’s story

The word nil is a noun that means nothing or zero. In the Go programming language, nil is a zero value. Recall from unit 2 that an integer declared without a value will default to 0. An empty string is the zero value for strings, and so on. A pointer with nowhere to point has the value nil. And the nil identifier is the zero value for slices, maps, and interfaces too.

Many programming languages incorporate the concept of nil, though they may call it NULL, null, or None. In 2009, prior to the release of Go, language designer Tony Hoare gave a presentation titled “Null References: The Billion Dollar Mistake.” In his talk (see mng.bz/dNzX), Hoare claims responsibility for inventing the null reference in 1965 and suggests that pointers to nowhere weren’t one of his brightest ideas.

Note

Tony Hoare went on to invent communicating sequential processes (CSP) in 1978. His ideas are the basis for concurrency in Go, the topic of unit 7.

Nil is somewhat friendlier in Go, and less prevalent than in past languages, but there are still caveats to be aware of. Nil has some unexpected uses too, which Francesc Campoy talked about in his presentation at GopherCon 2016 (see www.youtube.com/watch?v=ynoY2xz-F8s), providing inspiration for this lesson.

27.1. Nil leads to panic

27.2. Guarding your methods

27.3. Nil function values

27.4. Nil slices

27.5. Nil maps

27.6. Nil interfaces

27.7. An alternative to nil

Summary