如何将变量长度参数作为参数传递给Golang中的另一个函数?

时间:2014-11-27 11:04:56

标签: function go variadic-functions

如何在Go中传递可变长度参数?例如,我想打电话

func MyPrint(format string, args ...interface{}) {
  fmt.Printf("[MY PREFIX] " + format, ???)
}

// to be called as: MyPrint("yay %d", 213) 
//              or  MyPrint("yay")
//              or  MyPrint("yay %d %d",123,234)

1 个答案:

答案 0 :(得分:80)

啊发现它...接受可变长度参数的函数称为 Variadic Functions 。例如:

package main

import "fmt"

func MyPrint(format string, args ...interface{}) {
  fmt.Printf("[MY PREFIX] " + format, args...)
}

func main() {
 MyPrint("yay %d %d\n",123,234);
 MyPrint("yay %d\n ",123);
 MyPrint("yay %d\n");
}