英文:
How to pass variable length arguments as arguments on another function in Golang?
问题
如何在Go
中传递可变长度的参数?例如,我想调用以下函数:
func MyPrint(format string, args ...interface{}) {
fmt.Printf("[MY PREFIX] " + format, ???)
}
可以这样调用:
MyPrint("yay %d", 213)
MyPrint("yay")
MyPrint("yay %d %d", 123, 234)
英文:
How to pass variable length arguments in Go
? for example, I want to call
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
得分: 109
啊,找到了...接受可变长度参数的函数被称为可变参数函数。示例代码如下:
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");
}
英文:
Ah found it...functions that accept variable length arguments are called Variadic Functions. Example:
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");
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论