English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Functions called with a different number of parameters are called variadic parameter functions. In other words, it allows users to pass zero or more parameters in a variadic function.fmt.PrintfThis is an example of a variadic parameter function, which requires a fixed parameter at the beginning and can accept any number of parameters thereafter.
Important事项:
In the declaration of a variadic parameter function, the type of the last parameter is preceded by an ellipsis, i.e., (…)。It indicates that the function can call an arbitrary number of parameters of this type
Syntax:
function function_name(para1, para2...type)type{ // code... }
function function …typeofBehavior is similar to a slice (slice). For example, assume we have a function signature, i.e., add(b…int)int, which is now a parameter of type [] int.
You can also pass existing slices in a variable parameter function. For this, we pass a part of the complete array to the function, as shown below.Example2As shown.
When you do not pass any parameters to a variable parameter function, the default inside the function is nil.
Variable parameter functions are usually used for string formatting.
You can also pass multiple slices in a variable parameter function.
You cannot use variable parameters as a return value, but you can return them as a slice.
Demonstration example of zero and multiple parameters:
package main import ( "fmt" "strings" ) //Variable parameter function string concatenation func joinstr(element ...string) string { return strings.Join(element, "-") } func main() { //Zero parameters fmt.Println(joinstr()) //Multiple parameters fmt.Println(joinstr("GEEK", "GFG")) fmt.Println(joinstr("Geeks", "for", "Geeks")) fmt.Println(joinstr("G", "E", "E", "k", "S")) }
Output:
GEEK-GFG Geeks-for-Geeks G-E-E-k-S
Example2, variable parameter function string concatenation, passing a slice in a variable function:
package main import( "fmt" "strings" ) //Variable parameter function string concatenation func joinstr(element...string)string{ return strings.Join(element, "-") } func main() { //Passing a slice in a variable function element:= []string{"geeks", "FOR", "geeks"} fmt.Println(joinstr(element...)) }
Output:
geeks-FOR-geeks
When using a variable parameter function:
Use a variable parameter function when you need to pass a slice to a function.
Use a variable parameter function when you are unsure of the number of parameters.
When using a variable parameter function in a program, it can enhance the readability of the program.