You’ve been using fmt.Println to print results to the screen, and you’ve probably noticed that this function allows any number of input parameters. How does it do that?
Like many languages, Go supports variadic parameters (which just means a function can have an unspecified number of parameters). It does so via a special variadic parameter, which must be the last (or only) parameter in the input parameter list. You indicate it with three dots (...) before the type. The variable that’s created within the function is a slice of the specified type. You use it just like any other slice.
func addTo(base int, vals ...int) []int {
out := make([]int, 0, len(vals))
for _, v := range vals {
out = append(out, base+v)
}
return out
}
Now call it in a few ways:
func main() {
fmt.Println(addTo(3))
fmt.Println(addTo(3, 2))
fmt.Println(addTo(3, 2, 4, 6, 8))
a := []int{4, 3}
fmt.Println(addTo(3, a...))
fmt.Println(addTo(3, []int{1, 2, 3, 4, 5}...))
}
As you can see, you can supply however many values you want for the variadic parameter or no values at all. Since the variadic parameter is converted to a slice, you can supply a slice as the input. However, you must put three dots (...) after the variable or slice literal. If you don’t, you’ll get a compile-time error.
When you build and run this program, you get this output:
[]
[5]
[5 7 9 11]
[7 6]
[4 5 6 7 8]