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

huangapple go评论87阅读模式
英文:

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");
}

huangapple
  • 本文由 发表于 2014年11月27日 19:04:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/27169110.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定