Variadic Functions
In this page:
Declaring a Variadic Function
Prefixing the last parameter's type with '...' lets the caller pass any number of arguments of that type, including none at all -- inside the function, that parameter is just a regular slice.
Example: Declaring a Variadic Function
package main
import "fmt"
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println(sum(1, 2, 3, 4))
fmt.Println(sum())
}
Login to try C/C++/Java/PHP code in the editor
Spreading a Slice into Variadic Arguments
If you already have a slice and want to pass its elements as individual variadic arguments, append '...' after the slice at the call site instead of passing the slice as one value.
Example: Spreading a Slice into Variadic 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(values...))
}
Login to try C/C++/Java/PHP code in the editor
Mixing Regular and Variadic Parameters
A variadic parameter can be combined with regular parameters before it, as long as it remains the final parameter in the list -- a common pattern for functions like a formatted logger that always takes a prefix plus a variable number of values.
Note: Variadic parameters must always come last in the signature.
Example: Mixing Regular and Variadic Parameters
package main
import "fmt"
func logAll(prefix string, values ...int) {
for _, v := range values {
fmt.Println(prefix, v)
}
}
func main() {
logAll("value:", 1, 2, 3)
}
Login to try C/C++/Java/PHP code in the editor
- Forgetting the variadic parameter must be last in the parameter list -- Go only allows one, at the very end.
- Trying to pass a slice directly to a variadic parameter without the '...' spread operator, which fails to compile.
- Assuming a variadic function can accept zero arguments and behave the same as passing an empty slice, without checking len() first.
- A variadic parameter, written as '...Type', lets a function accept any number of arguments of that type.
- Inside the function, the variadic parameter behaves like a regular slice.
- An existing slice can be passed to a variadic parameter using the spread operator, slice...
- Only the last parameter in a function signature may be variadic.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: