英文:
Variadic functions parameters pass-through
问题
Situation:
我正在尝试编写一个简单的fmt.Fprintf
包装器,它可以接受可变数量的参数。以下是代码:
func Die(format string, args ...interface{}) {
str := fmt.Sprintf(format, args)
fmt.Fprintf(os.Stderr, "%v\n", str)
os.Exit(1)
}
Problem:
当我使用Die("foo")
调用它时,我得到以下输出(而不是"foo"):
foo%!(EXTRA []interface {}=[])
- 为什么在"foo"之后会有"%!(EXTRA []interface {}=[])"?
- 如何正确地创建
fmt.Fprintf
的包装器?
英文:
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\n", 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
?
答案1
得分: 66
变长函数将参数作为类型为[]interface{}
的切片接收。在这种情况下,您的函数接收一个名为args
的[]interface{}
类型的参数。当您将该参数传递给fmt.Sprintf
时,您将其作为类型为[]interface{}
的单个参数传递。您真正想要的是将args
中的每个值作为单独的参数传递(与接收它们的方式相同)。要做到这一点,您必须使用...
语法。
str := fmt.Sprintf(format, args...)
这也在Go规范中解释了这里。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论