Go-可变参数函数传递

Go-可变参数函数传递

问题描述:

Situation:

I'm trying to write a simple fmt.Fprintf wrapper which takes a variable number of arguments. This is the code:

func Die(format string, args ...interface{}) {
    str := fmt.Sprintf(format, args)
    fmt.Fprintf(os.Stderr, "%v
", str)
    os.Exit(1)
}

Problem:

When I call it with Die("foo"), I get the following output (instead of "foo"):

foo%!(EXTRA []interface {}=[])

  • Why is there "%!(EXTRA []interface {}=[])" after the "foo"?
  • What is the correct way to create wrappers around fmt.Fprintf?

情况: strong> p>

我正在尝试 编写一个简单的 fmt.Fprintf code>包装器,该包装器使用可变数量的参数。 这是代码: p>

  func Die(格式字符串,args ... interface {}){
 str:= fmt.Sprintf(format,args)
 fmt  .Fprintf(os.Stderr,“%v 
”,str)
 os.Exit(1)
} 
  code>  pre> 
 
 

问题: p>

当我用 Die(“ foo”) code>调用它时,我得到以下输出(而不是“ foo em> “): p>

foo%!(额外[]接口{} = []) p> blockquote>

  • 为什么在“ foo em>”后面有“ %!(EXTRA [] interface {} = []) em>”? li> 在 fmt.Fprintf code>周围创建包装的正确方法是什么? li> ul> div>

Variadic functions receive the arguments as a slice of the type. In this case your function receives a []interface{} named args. When you pass that argument to fmt.Sprintf, you are passing it as a single argument of type []interface{}. What you really want is to pass each value in args as a separate argument (the same way you received them). To do this you must use the ... syntax.

str := fmt.Sprintf(format, args...)

This is also explained in the Go specification here.