How to Write a Variadic Function in Go
A variadic function accepts any number of values for its last parameter: none, one or many. fmt.Println is one. You write your own by putting ... before the parameter's type, and inside the function the values arrive as a slice.
Syntax
func <name>(<values> ...<type>) {
// <values> is a []<type>
}
<name>(<a>, <b>, <c>)
<name>(<slice>...)
| Part | What it does |
|---|---|
...<type> | Lets the last parameter take any number of values. |
<values> inside the function | A slice of those values, empty when none were passed. |
<slice>... | Passes an existing slice's items as the separate values. |
The Go specification: "If f is variadic with a final parameter p of type ...T, then within f the type of p is equivalent to type []T."
The Example
The example writes sum, which adds up however many numbers it gets, and calls it three ways.
Prerequisites
- Go.
go runcompiles and runs a single file. This guide uses Go 1.27.4.
Step 1: Write the Function
Create a file named main.go:

package main
import "fmt"
func sum(numbers ...int) int {
total := 0
for _, n := range numbers {
total += n
}
return total
}
func main() {
fmt.Println(sum())
fmt.Println(sum(1, 2, 3))
values := []int{4, 5, 6}
fmt.Println(sum(values...))
}
for _, n := range numbers visits each number in the slice; _ skips the position, which isn't needed.
Step 2: Run It
go run main.go
0
6
15

sum()received an empty slice, so the total stayed0.sum(1, 2, 3)received three numbers.sum(values...)spread the slice into separate values.
The command is the same in zsh, bash and PowerShell.
Common Mistakes
| Mistake | What happens | Do this instead |
|---|---|---|
Passing a slice without ..., as in sum(values) | cannot use values (variable of type []int) as int value in argument to sum | Write sum(values...) |
| Putting the variadic parameter before another one | can only use ... with final parameter | Move it to the end |
Mixing single values with a spread slice, as in sum(1, values...) | too many arguments in call to sum | Pass either single values or one spread slice |
Troubleshooting
| Symptom | Likely cause | Fix |
|---|---|---|
cannot use … (variable of type []int) as int value | A slice went in where single values were expected | Add ... after it |
| The function sees no values | It was called without arguments | Expect an empty slice and handle it |
FAQ
Is fmt.Println variadic?
Yes: its parameter is a ...any, which is why it takes any number of values of any type.
Can there be other parameters before the variadic one?
Yes, as in func join(sep string, parts ...string); only the last parameter can be variadic.
Conclusion
Put ... before the last parameter's type and the function takes any number of values, which it sees as a slice. Spread an existing slice into it with slice....
Additional Resources
- Passing arguments to ... parameters, in the Go specification.
