Variable parameter function:
The number of formal parameters in a function is usually deterministic, and in turn, all the actual arguments corresponding to the formal parameters are passed in sequence, but in some functions the number of arguments can be determined according to the actual need, which is the variable parameter function.
the Go language supports variable-length arguments, but it is important to note that the variable length parameter can only be used as the last parameter of the function and not in front of other parameters. The declaration of the function is as follows:
Func functionname (Variableargumentname ... datetype) return value {
Body
}
The essence of an indefinite long variable is a slice that can be traversed using a range , for example :
Func f (args ... int) {
For _,arg: =range args{
Fmt. PRINTLN (ARG)
}
}
We are familiar with the FMT. The Print () function can pass different types of arguments,and thego language specifies that if you want to pass any type of argument, the argument type should be set to an empty interface type:interface{}. For example:
Func F (args ... interface{}) {
...
}
In the Go language, an empty interface can point to any data object, so you can use interface{} to define any type of variable, while interface{} is also type-safe.
Cases:
Package Main
Import (
"FMT"
)
Func Main () {
F (2, "Go", 8, "language", ' a ', false, ' a ', 3.14)
}
Func f (args ... interface{}) {
var num = make ([]int, 0, 6)
var str = make ([]string, 0, 6)
var ch = make ([]int32, 0, 6)
var other = make ([]interface{}, 0, 6)
For _, arg: = Range args {
Switch V: = arg. (type) {
Case INT:
num = append (num, v)
Case string:
str = append (str, v)
Case Int32:
ch = append (ch, v)
Default
other = append (Other, V)
}
}
Fmt. PRINTLN (num)
Fmt. Println (str)
Fmt. PRINTLN (CH)
Fmt. Println (Other)
}
Output:
[2 8]
[Go language]
[97 65]
[False 3.14]
The variable parameter function is not very difficult, understand and understand, then write, and then try some of their own variable parameter function can be
Go language: Variable parameter function