Iterating Over Nil Slices in Go

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!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: