Home > Article > Backend Development > The principle and usage of Golang function varargs parameters
In the Go language, use the ... symbol to declare varargs parameters, which allows the function to receive a variable number of parameters of the same type. The varargs parameter creates a slice behind the scenes that stores all extra parameters and makes elements accessible by index. In this case, the sumVarargs function uses the varargs parameter to calculate the sum of any number of int parameters. The varargs parameter must be the last parameter and a default value cannot be specified.
Varargs parameters in Go language: Principle and usage
In Go language, varargs parameters allow functions to accept a variable number of parameter. This functionality is implemented using the ...
notation, which indicates that the function can receive any number of arguments of the same type.
How it works: The
varargs parameter creates a slice named args
behind the scenes that contains all the extra arguments received by the function. The slice is part of the function variable and allows the function to access it.
Declaration:
To declare a varargs parameter, just add the ...
symbol to the function signature, followed by the name of the type, as follows Shown:
func myFunction(a int, b string, c ...int) { // 函数代码 }
In this example, myFunction
accepts three parameters: a
(type is int
), b
(of type string
) and a variable number of int
arguments, stored in a c
slice.
Usage:
varargs parameters can be used in functions like any other parameters. For example, elements in the c
slice can be accessed by index:
func sumVarargs(nums ...int) int { sum := 0 for _, num := range nums { sum += num } return sum }
Practical example:
The following is a calculation of the sum of any number of parameters using the varargs parameter Case:
package main import "fmt" func sumVarargs(nums ...int) int { sum := 0 for _, num := range nums { sum += num } return sum } func main() { total := sumVarargs(1, 2, 3, 4, 5) fmt.Println("Total:", total) // 输出:15 }
In this case, the sumVarargs
function receives any number of int
arguments using the varargs parameter (nums
) and calculates their sum.
Additional instructions:
The above is the detailed content of The principle and usage of Golang function varargs parameters. For more information, please follow other related articles on the PHP Chinese website!