Variadic Functions
Accepting a variable number of arguments
What Is a Variadic Function?
A variadic function accepts zero or more arguments of a specified type, collected into a slice:
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
fmt.Println(sum(1, 2, 3, 4)) // 10The ...T Syntax
Use ...T as the last parameter type. Inside the function, it is a []T:
- Can be called with 0 or more arguments
- The variadic parameter must be the last one
- Only one variadic parameter per function