GoLang Varidadic Functions
December 20, 2020
Its often that I see people refer to go syntax as “simple”
I hardly find it so. I chronically forget some of Go’s
basic syntax. Specifically recently I had to look up what the
... operator is. It seems that the ... operator is
for specifying the inputs to “Variadic” functions.
Wikipedia tells me that a variadic funcion is a function
of indefinite arity, i.e., one which accepts a variable
number of arguments
Go figure.
Go By Example has this pretty well authored here, I’ve copy-pasta-ed it below:
package main
import "fmt"
func sum(nums ...int) {
fmt.Print(nums, " ")
total := 0
for _, num := range nums {
total += num
}
fmt.Println(total)
}
func main() {
sum(1, 2)
sum(1, 2, 3)
nums := []int{1, 2, 3, 4}
sum(nums...)
}
Note the ... is before the type on the function argument definition and
when the function is called with a slice arguement the ... follows
the slice.
I’m not sure how smartly you can mix this variadic input, for example does the variadic argument need to be last? Can I have more then one variadic input type? IDK. Researching that another day.