Slices are one of the most common data types used in Go. They provide a way for to work with and manage collections of data, and can be appended to or iterated over. But what’s a nil slice and how does it differ from an empty slice? Let’s find out.
A nil slice is one that is declared without being initialised. It has a length and capacity of
0 with no underlying array, and it’s zero value is
nil. Nil slices are useful to represent a collection that does not exist yet.
An empty slice is one that contains zero elements. It has an underlying array, but with zero elements. An empty slice is handy for representing an empty collection, such as when a query yields no results.
What’s the difference?
For the most part, there’s actually no observable difference between nil slices and empty slices. The built-in functions
cap all work in the same way for both, and you can
for...range over either with the same result (0 iterations).
There’s a subtle difference though. As mentioned earlier,
nil slices are great for collections that do not exist yet, while empty slices are for empty collections. This is exemplified when encoding to JSON:
As you can see, the
nil slice gets encoded as
null while the empty slice becomes an empty JSON array. You need to guard against returning the wrong value from your API, as it could easily violate your API spec leading to bugs and unhappy customers.
Thanks for reading, and happy coding!