如何将可变参数传递给其他函数

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

How to pass variadic argumens to other functions

问题

函数Warn可以通过以下方式来使其工作吗?

func Warn(s string, args ...interface{}) {
    log.Printf("warn: "+s, args)
}

func main() {
    Warn("%d个苹果,%s ", 10, "好") //它应该输出与下面相同的结果
    log.Printf("%d个苹果,%s ", 10, "好")
}

输出结果:

2009/11/10 23:00:00 warn: [10 %!d(string=good)]个苹果,%s(MISSING) 
2009/11/10 23:00:00 10个苹果,好

我正在尝试使其工作:http://play.golang.org/p/W62f2NGDUe

英文:

Is there any way the function Warn could be made to work?

func Warn(s string, args ...interface{}) {
	log.Printf("warn: "+s, args)
}

func main() {
	Warn("%d apples, %s ", 10, "good") //it should output the same as below
	log.Printf("%d apples, %s ", 10, "good")
}

Output:

2009/11/10 23:00:00 warn: [10 %!d(string=good)] apples, %s(MISSING) 
2009/11/10 23:00:00 10 apples, good

I'm trying to make this work: http://play.golang.org/p/W62f2NGDUe

答案1

得分: 8

func Warn(s string, args ...interface{}) {
log.Printf("警告: "+s, args...)
}

现在它可以工作了。

英文:

Got it:

func Warn(s string, args ...interface{}) {
    log.Printf("warn: "+s, args...)
}

Now it works.

huangapple
  • 本文由 发表于 2013年7月11日 00:48:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/17576378.html
匿名

发表评论

匿名网友

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

确定