Home >Backend Development >Golang >golang function variable parameter passing
Go language function variable parameter passing allows a function to accept any number of parameters, marked by an ellipsis..., and passed to the function as a slice type. In practical applications, variable parameters are often used to process an indefinite number of inputs, such as calculating the average of a numerical sequence. When using it, please note that the variable parameter must be the last parameter of the function, avoid overuse, and consider explicit type assertion.
In the Go language, function variable parameter passing allows the function to accept a number Indefinite parameters, which are useful when you need to handle an indefinite number of inputs.
Variable parameter passing is marked using ...
(ellipsis) in the function declaration, as follows:
func myFunc(arg1 string, args ...int) {}
Here, myFunc
The function receives the first parameter as a string arg1
, and subsequent parameters as variable parameters args
, and as a type of []int The slice of
is passed to the function.
Consider a scenario where you need to write a function to calculate the average of a given sequence of numbers:
package main import "fmt" // 计算数字序列平均值的函数 func average(numbers ...int) float64 { total := 0 for _, number := range numbers { total += number } return float64(total) / float64(len(numbers)) } func main() { // 使用可变参数调用 average 函数 numbers := []int{10, 20, 30, 40, 50} result := average(numbers...) // 打印平均值 fmt.Println("平均值:", result) }
In this case:
average
Function declaration has variadic parameters numbers
. main
Use ellipsis ...
to expand the numbers
slice and pass it as a variable parameter to average
function. When using variable parameter transfer, you need to pay attention to the following:
The above is the detailed content of golang function variable parameter passing. For more information, please follow other related articles on the PHP Chinese website!