Sometimes you don’t know how many arguments you’ll get — a party might have one hero or six. A variadic function accepts any number of them using ...:
func shout(words ...string) {
for _, w := range words {
fmt.Println(w)
}
}
shout("for", "the", "realm")
Inside the function, the variadic parameter is just a slice.
Functions are also values in Go, and a closure is a function that captures variables from around it — handy for counters and generators:
func counter() func() int {
n := 0
return func() int { n++; return n }
}
next := counter()
fmt.Println(next(), next()) // 1 2
Your Quest
Write a variadic function total that takes any number of ints and returns their sum.
Expected output:
60
Hint
Declare func total(nums ...int) int, then for _, n := range nums { sum += n } and return sum.