A variadic function is a function that accepts a variable number of arguments. In Golang, it is possible to pass a varying number of arguments of the same type as referenced in the function signature.
In Golang, we declare a function using the func keyword. A function has a name, a list of comma-separated input parameters along with their types, the result type(s), and a body. The input parameters and return type(s) are optional for a function. A function can be declared without any input and output.
Variadic functions are functions (e.g. printf) which take a variable number of arguments.
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"}
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,))
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With