generativist / til

Go Variadics Work with Nil Slices

Another, "Oh Right, of Course They Do" Moment

Variadic functions are useful in Go, especially as a means of implementing function options to get around the language’s lack of optional arguments. What I didn’t realize realize somehow until today is that you can expand a nil slice without any problem. To illustrate the point with a simple example, let’s say you have,

func Sum(items ...int) int {
var acc int
for _, item := range items {
acc += item
}
return acc
}

The sum works as you would expect given a sequence of arguments,

Sum(1, 2, 3)
6

But it also works correctly for nil slice,

var items []int = nil // Note: The assigment is redundant

Sum(items...)
0

In retrospect, it seems obvious that the design would anticipate this case. But, well…

…I didn’t know.