Home »
Golang
Go Variadic Functions
Last Updated : July 21, 2025
In Go, a variadic function is a function that can accept a variable number of arguments of the same type. It is useful when you don't know in advance how many values will be passed to the function, such as summing numbers or formatting strings.
Define a Variadic Function
To define a variadic function, use an ellipsis (...
) before the type of the last parameter.
func functionName(arg ...datatype) {
// function body
}
Example: Sum of Numbers
The following example shows how to use variadic functions in Go, allowing a function to accept a variable number of arguments:
package main
import "fmt"
func sum(numbers ...int) int {
total := 0
for _, num := range numbers {
total += num
}
return total
}
func main() {
fmt.Println("Sum of 3, 5:", sum(3, 5))
fmt.Println("Sum of 1, 2, 3, 4:", sum(1, 2, 3, 4))
}
When you run the above code, the output will be:
Sum of 3, 5: 8
Sum of 1, 2, 3, 4: 10
Passing a Slice to a Variadic Function
You can also pass a slice to a variadic function using the ...
operator.
Example
The following example demonstrates how to pass a slice to a variadic function in Go using the ...
syntax:
package main
import "fmt"
func display(names ...string) {
for _, name := range names {
fmt.Println("Hello", name)
}
}
func main() {
friends := []string{"Alice", "Bob", "Charlie"}
display(friends...) // Passing slice to variadic function
}
When you run the above code, the output will be:
Hello Alice
Hello Bob
Hello Charlie
Explanation
- In
sum()
, any number of int
arguments can be passed.
- In
display()
, a slice of strings is expanded into individual arguments using ...
.
- Variadic parameters must be the last in the function signature.
Go Variadic Functions Exercise
Select the correct option to complete each statement about variadic functions in Go.
- What symbol is used to declare a variadic parameter?
- Can you pass a slice to a variadic function?
- Which of the following function signatures is correct?
Advertisement
Advertisement