Variadic Functions
A variadic function accepts a variable number of arguments via the ...T parameter - the basis of fmt.Println, append, and ergonomic APIs.
A variadic parameter accepts zero or more arguments of one type. It must be the final parameter, and inside the function it behaves as a slice.
Pass separate values as usual. To pass an existing slice, add ... at the call site to supply its elements as arguments.
package main
import "fmt"
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
values := []int{10, 20, 30}
fmt.Println(sum(1, 2, 3))
fmt.Println(sum(values...))
}In production
Passing values... passes a slice backed by the caller's array. Mutating an element through the variadic parameter changes the caller's data, and append may reuse spare capacity. Prefer an explicit slice parameter when ownership or mutation should be clear.
Enjoyed this? Get more software craft delivered to your inbox.