How to Use Variadic Functions in Go: Syntax and Examples
In Go, a
variadic function accepts zero or more arguments of a specified type using the syntax func name(args ...type). You can call it with any number of arguments or pass a slice with ... to expand it.Syntax
A variadic function in Go is declared by placing ... before the type of the last parameter. This means the function can accept any number of arguments of that type.
- func: keyword to declare a function
- name: function name
- args ...type: variadic parameter that accepts zero or more values of
type
Inside the function, args behaves like a slice of type.
go
func example(args ...int) { // args is a slice of int }
Example
This example shows a variadic function sum that adds any number of integers and returns the total.
go
package main import "fmt" func sum(numbers ...int) int { total := 0 for _, num := range numbers { total += num } return total } func main() { fmt.Println(sum(1, 2, 3)) // Call with 3 arguments fmt.Println(sum(10, 20)) // Call with 2 arguments nums := []int{4, 5, 6} fmt.Println(sum(nums...)) // Pass slice with ... to expand }
Output
6
30
15
Common Pitfalls
Common mistakes when using variadic functions include:
- Forgetting to use
...when passing a slice to a variadic parameter. - Trying to have multiple variadic parameters (only one is allowed and it must be last).
- Misunderstanding that inside the function, the variadic parameter is a slice.
go
package main import "fmt" // Wrong: multiple variadic parameters // func wrong(a ...int, b ...string) {} func correct(a ...int) { fmt.Println(a) } func main() { nums := []int{1, 2, 3} // Wrong: missing ... when passing slice // correct(nums) // This will cause a compile error // Right: use ... to expand slice correct(nums...) }
Output
[1 2 3]
Quick Reference
| Concept | Description | Example |
|---|---|---|
| Variadic parameter | Use ...type to accept multiple arguments | func f(nums ...int) |
| Call with values | Pass any number of arguments directly | f(1, 2, 3) |
| Call with slice | Expand slice with ... | f(slice...) |
| Inside function | Variadic args behave like a slice | for _, v := range nums {} |
| Only one variadic | Only last parameter can be variadic | No multiple ...type params |
Key Takeaways
Declare variadic functions with
func name(args ...type) to accept multiple arguments.Inside the function, the variadic parameter is a slice you can loop over.
Pass a slice to a variadic function by adding
... after the slice variable.Only one variadic parameter is allowed and it must be the last parameter.
Common errors include forgetting
... when passing slices and trying multiple variadic parameters.