Archive

Monthly Archives: April 2017

Go has some interesting quirks.

Recently I learned you can iterate over nil slices.

Here’s an example:

var foo []string // nil slice
var bar = []string{} // empty slice

fmt.Println(foo == nil) // true
fmt.Println(bar == nil) // false

for _, v := range foo { // no errors
	fmt.Println("%v", v)
}

for _, v := range bar { // no errors
	fmt.Println("%v", v)
}

Normally, I avoid returning nils in functions, to reduce the need for a nil check before iterating, but looks like Go has it built in.

Neat!