A variadic function in Go accepts a variable number of arguments. You can define a variadic function by using the … syntax before the type of the last parameter. This suggests that the function can accept any number of arguments of that type, which will be accessible within the function as a slice.
Example
package main
import (
"fmt"
)
func Sum(nums ...int) int {
total := 0
for _, num := range nums {
total += num
}
return total
}
func main() {
fmt.Println(Sum())
fmt.Println(Sum(1, 2))
fmt.Println(Sum(1, 2, 3, 4, 5, 6))
numbers := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
fmt.Println(Sum(numbers...))
}
Output
0
3
21
55
In this code example, we defined a Sum() variadic function that accepts any number of integers.
The nums parameter is a slice that contains all the integer arguments passed to the function. Inside the function, we iterated through the nums slice and calculated the sum of the integers.
Inside the main() function, we demonstrated different ways to call the Sum() variadic function with no arguments, two arguments, multiple arguments, and by passing a slice of integers using the … syntax.
A variadic function provides flexibility in handling a variable number of arguments and is commonly used for functions like fmt.Printf() can format various values based on the format string.
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.