Accept variadic arguments
Accept variadic arguments
A variadic function accepts zero or more arguments for its final parameter, written values ...int. Inside the function, values behaves as a slice: an ordered sequence with a length, introduced fully in the Slices chapter. A range loop can visit its elements.
package main
import "fmt"
func sum(values ...int) int { total := 0 for _, v := range values { total += v } return total}func main() { fmt.Println(sum(2, 3, 4)) fmt.Println(sum())}In for _, v := range values, the blank identifier ignores the index and v receives each element. With zero arguments the variadic slice is nil and has length zero, so the loop executes zero times.
Expand an existing slice
package main
import "fmt"
func sum(values ...int) int { total := 0 for _, v := range values { total += v } return total}func main() { numbers := []int{4, 5, 6} fmt.Println(sum(numbers...))}[]int{4,5,6} constructs a slice of integers. numbers... passes it as the variadic argument without creating a new slice for the parameter. Do not write sum(numbers) because a slice is not an int. For a single variadic parameter, do not mix individual elements with a slice expansion in the same call.
Try it locally
Write countPositive(values ...int) int counting strictly positive numbers. Print results for (-1, 0, 2, 5) and no arguments.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functions 05: Accept variadic arguments
Check the lesson objective before moving on.
Where may a variadic parameter appear?
How do you pass a []int to sum(values ...int)?