问题描述
情况:
我正在尝试编写一个简单的 fmt.Fprintf
包装器,该包装器使用可变数量的参数.这是代码:
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\n", str)
os.Exit(1)
}
问题:
当我用 Die("foo")
调用它时,得到以下输出(而不是" foo "):
When I call it with Die("foo")
, I get the following output (instead of "foo"):
- 为什么在" foo "之后有"%!(EXTRA [] interface {} = [])"?
- 在
fmt.Fprintf
周围创建包装的正确方法是什么? - Why is there "%!(EXTRA []interface {}=[])" after the "foo"?
- What is the correct way to create wrappers around
fmt.Fprintf
?
推荐答案
可变参数函数将参数作为类型的切片接收.在这种情况下,您的函数将收到名为 args
的 [] interface {}
.当您将该参数传递给 fmt.Sprintf
时,您会将其作为类型为 [] interface {}
的单个参数传递.您真正想要的是将 args
中的每个值作为单独的参数传递(与接收它们的方式相同).为此,您必须使用 ...
语法.
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...)
Go规范此处也对此进行了解释.
This is also explained in the Go specification here.
这篇关于可变参数函数传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!