Variadic Functions in Go
Variadic functions in Go allow you to pass a variable number of arguments to a function. This feature is useful when you don’t know beforehand how many arguments you will pass. A variadic function accepts multiple arguments of the same type and can be called with any number of arguments, including none.
Example:
package main
import "fmt"
// Variadic function to calculate sum
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println("Sum of 1, 2, 3:", sum(1, 2, 3))
fmt.Println("Sum of 4, 5:", sum(4, 5))
fmt.Println("Sum of no numbers:", sum())
}
Output
Sum of 1, 2, 3: 6 Sum of 4, 5: 9 Sum of no numbers: 0
Syntax
func functionName(parameters ...Type) ReturnType {
// Code
}
In the syntax above:
parameters ...Type
indicates that the function can accept a variable number of arguments of typeType
.- You can access the arguments within the function as a slice.
Table of Content
Using Variadic Functions
When defining a variadic function, you specify the type of the arguments followed by an ellipsis (...
) as shown in the above example. Inside the function, these arguments can be treated as a slice.
Calling a Variadic Function
You can call a variadic function with any number of arguments, including zero. The function treats the arguments as a slice.
Example:
package main
import "fmt"
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println("Sum of 1, 2, 3:", sum(1, 2, 3))
fmt.Println("Sum of 4, 5:", sum(4, 5))
fmt.Println("Sum of no numbers:", sum())
}
Output
Sum of 1, 2, 3: 6 Sum of 4, 5: 9 Sum of no numbers: 0
Variadic Functions with Other Parameters
You can also mix variadic parameters with regular parameters in a function. The variadic parameter must always be the last parameter.
Example:
package main
import "fmt"
// Variadic function to calculate sum
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Function with a regular parameter and a variadic parameter
func greet(prefix string, nums ...int) {
fmt.Println(prefix)
for _, n := range nums {
fmt.Println("Number:", n)
}
}
func main() {
greet("Sum of numbers:", 1, 2, 3)
greet("Another sum:", 4, 5)
greet("No numbers sum:")
}
Output
Sum of numbers: Number: 1 Number: 2 Number: 3 Another sum: Number: 4 Number: 5 No numbers sum:
Limitations of Variadic Functions
- Variadic functions can only have one variadic parameter, and it must be the last parameter.
- You cannot have multiple variadic parameters in a single function definition.