Golang offers a unique feature called variadic functions, which allows you to define functions that accept an arbitrary number of arguments. This provides a flexible way to handle functions with varying inputs.
In your example, you wish to define a function Add that takes any number of integers and returns their sum. In Go, you can achieve this using the syntax ...int, where the ellipsis (...) indicates the variable number of arguments. Here's a corrected version of your example:
package main import "fmt" func Add(num1 ...int) int { sum := 0 for _, v := range num1 { sum += v } return sum } func main() { fmt.Println("Hello, playground") fmt.Println(Add(1, 3, 4, 5)) }
As the spec mentions:
Given the function and call
func Greeting(prefix string, who ...string) Greeting("hello:", "Joe", "Anna", "Eileen")Copy after loginwithin Greeting, who will have the value []string{"Joe", "Anna", "Eileen"}
Therefore, when calling Add(1, 3, 4, 5), the num1 parameter will be a slice of integers containing the values [1, 3, 4, 5]. This slice can then be iterated to calculate the sum of the input numbers.
The above is the detailed content of How Do Variadic Functions in Go Handle an Arbitrary Number of Arguments?. For more information, please follow other related articles on the PHP Chinese website!