Does Golang support variadic function?
I wonder if there a way where I can define a function for unknown number of variables in Go.
Something like this
func Add(num1... int) int {
return args
}
func main() {
fmt.Println("Hello, playground")
fmt.Println(Add(1, 3, 4, 5,))
}
I want to generalize the function Add
for any number of inputs.
Solution 1:
You've pretty much got it, from what I can tell, but the syntax is ...int
. See the spec:
Given the function and call
func Greeting(prefix string, who ...string) Greeting("hello:", "Joe", "Anna", "Eileen")
within Greeting,
who
will have the value[]string{"Joe", "Anna", "Eileen"}
Solution 2:
While using the variadic parameters, you need to use loop in the datatype inside your function.
func Add(nums... int) int {
total := 0
for _, v := range nums {
total += v
}
return total
}
func main() {
fmt.Println("Hello, playground")
fmt.Println(Add(1, 3, 4, 5,))
}
Solution 3:
Golang have a very simple variadic function declaration
Variadic functions can be called with any number of trailing arguments. For example, fmt.Println
is a common variadic function.
Here’s a function that will take an arbitrary number of int
's as arguments.
package main
import (
"fmt"
)
func sum(nums ...int) {
fmt.Println(nums)
for _, num := range nums {
fmt.Print(num)
}
}
func main() {
sum(1, 2, 3, 4, 5, 6)
}
Output of the above program:
[1 2 3 4 5 6]
1 2 3 4 5 6