Image generated on PicturetoPeople

Better Than Nothing?

A Go Brain Teaser

Miki Tebeka
3 min readJan 25, 2022

--

📚 Connect with us. Want to hear what’s new at The Pragmatic Bookshelf? Sign up for our newsletter. You’ll be the first to know about author speaking engagements, books in beta, new books in print, and promo codes that give you discounts of up to 40 percent.

Happy 2022! Let’s kick this year off with some interesting puzzles. We’ll start with nothing :)

What do you think the following program will print?

This program will fail to compile with the error:

In Go, nilis not a type but a reserved word. A variable must have a type, even if it’s initialized to nil.

If you change line 8 to var n*int = nil the program will run and print <nil>.

Each type in Go has a zero value that is assigned to uninitialized variables. nil is the zero value for pointers, functions, interfaces, slices, channels, and maps. In some cases, the behavior of nil value might surprise you. Let’s have a look:

What do you think will happen when you run the following code?

Running this code will print login. Since we don’t try to access the ereceiver in Kind, we can call this method even on nilvalues.

What about the following code?:

This code will print len: 0, IBM: 0. len and map access are nil safe; however, if you try to assign a value (likestocks["IBM"] = 134.83) the code will panic. lenis also safe to use on nil slices and channels.

Let’s look at nilchannels:

This code panics with the error message: fatal error: all goroutines are asleep — deadlock!. Sending or receiving on a nil channel will block forever. If you are curious as to why, Francesc has a great explanation.

Our last type, interfaces, it even more interesting. Let’s see:

The code prints: ERROR <nil>. What?!

If you’ll look at runtime/runtime2.go in the Go standard library, you’ll see the following definition:

An interface is compromised of two pointers and is considered nil only if both underlying pointers are nil. In our case, the pointer to itab is not nil — and the returned error is not considered nil. This issue is confusing and common enough that it has its own FAQ entry.

Happy hacking! Stay safe out there.

--

--