A variadic function is a function that can take any number of arguments. A common use case for this is a function that can print out multiple things at once, and in fact Go’s fmt.Println()
function is a good example of this. It’s function signature is:
The ...{interface}
piece here denotes that Println
can take any number of arguments of type empty interface (i.e. anything). So this would work just fine:
Passing a Slice to a Variadic Function
If we want to pass a slice to a variadic function — i.e. if we want the function to accept each element of the slice as an input argument — we need to unpack it (I’m not sure if “unpack” is real Go terminology, but it’s the language I’m familiar with). We unpack it by adding a trailing ...
So, for example:
A common use case for this is appending a slice to another slice. We would need to unpack the second slice, e.g.: