You can traverse variable parameters in Go through the range keyword, which uses a for-range loop to traverse each value of the variable parameters. Alternatively, other methods can be used, such as the len() and index() functions, unpacking variadic arguments, or using the built-in reflect package.
How to traverse variable parameters in Go
In the Go language, variable parameters are used...
syntax means that it allows you to pass any number of parameters to the function. The method of traversing variable parameters is as follows:
Use range
keyword
func printValues(values ...int) { for _, value := range values { fmt.Println(value) } }
Practical case
Suppose we have a function that takes a variable number of integers and returns their sum. We can write this function by looping over the variadic arguments and using the
operator.
func sumValues(values ...int) int { var sum int for _, value := range values { sum += value } return sum } func main() { result := sumValues(1, 2, 3, 4, 5) fmt.Println("结果:", result) }
Output:
结果: 15
Other methods
In addition to the range
keyword, Other methods can be used to iterate over variadic parameters:
len()
and index()
functions: The len()
function returns the length of the variable argument, while the index()
function returns the argument at the specified index. reflect
package: reflect
package provides ValueOf()
and Len()
Function that can be used to obtain the type and length of variable parameters. The above is the detailed content of How to traverse variable parameters in golang?. For more information, please follow other related articles on the PHP Chinese website!