Variadic Functions in Golang
Question:
Is there a way to define a Go function that accepts an arbitrary number of arguments?
Solution:
Yes, Go supports variadic functions, which allow you to pass a variable number of arguments to a function. To define a variadic function, use the ellipsis (...) syntax followed by the type of the arguments you want to accept.
For example, here is a variadic function named Add that can accept any number of int arguments:
func Add(num1... int) int { sum := 0 for _, num := range num1 { sum += num } return sum }
You can call this function with any number of arguments, like this:
fmt.Println(Add(1, 3, 4, 5)) // Output: 13
Note:
In the example above, we used "..." (ellipsis) followed by "int" to indicate that the function accepts a variable number of int arguments. The variable named "num1" then represents a slice of integers, which contains all the arguments passed to the function.
The above is the detailed content of How Can I Create a Go Function with a Variable Number of Arguments?. For more information, please follow other related articles on the PHP Chinese website!