Does Go Support Functions with Variable Arguments?
In Go, you can create functions that can accept a variable number of arguments, known as variadic functions. This flexibility allows you to generalize functions to handle any number of inputs.
Example:
Consider the following code snippet where you aim to define a function Add that accepts an unknown number of integers:
func Add(num1... int) int { return args } func main() { fmt.Println("Hello, playground") fmt.Println(Add(1, 3, 4, 5)) }
In this code, the Add function is defined with ...int as the type of its final parameter. The syntax ... indicates that this parameter can accept multiple values of the specified type.
Solution:
As noted in the provided answer, the syntax for variadic parameters in Go is ...int, not just int. The revised code below demonstrates the correct usage:
func Add(num1... int) int { // Sum the numbers and return the result sum := 0 for _, n := range num1 { sum += n } return sum } func main() { fmt.Println("Hello, playground") fmt.Println(Add(1, 3, 4, 5,)) }
With this modification, you can use the Add function with any number of integers as arguments, providing the flexibility you sought.
The above is the detailed content of Can Go Functions Accept a Variable Number of Arguments?. For more information, please follow other related articles on the PHP Chinese website!