This is a creation in Article, where the information may have evolved or changed.
Indeterminate parameter types
An indeterminate parameter is a variable number of arguments passed in by a function.
package mainimport ( Span class= "hljs-string" > "FMT" ) /* indeterminate parameter function */ Func Add (a int , args ... int ) (Result int ) {result + = a for _, arg: = range args { Result + = arg} return }func Main () {FMT. Println (Add (1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 ,
Args in the code is an array slice and can only be placed in the last face of the parameter.
Transfer of indeterminate parameters
func SetData(args ...intint) { //不定参数的传递 return Add(1, args...)}func main() { fmt.Println(SetData(123))//输出7 array := []int{1234} fmt.Println(Add(1array...))//输出11}
Indefinite parameters of any type
/ * Any type of indeterminate parameter, denoted by interface{} * /funcmyprintf (args ...Interface{}) { for_, arg: =Rangeargs {//Iterative indeterminate parameters SwitchArg. (type) { Case int: FMT. Println (ARG,"is int") Case string: FMT. Println (ARG,"is string") Case float64: FMT. Println (ARG,"is Float64") Case BOOL: FMT. Println (ARG,"is bool")default: FMT. Println ("Unknown type") } }}funcMain () {/* Output: Haha int is string 12.5 is float64 false is bool-12.5 is float64 * /myprintf(,"haha",12.5,false,-12.5)}