可变参数函数参数传递

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

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.

huangapple
  • 本文由 发表于 2012年9月9日 05:36:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/12334697.html
匿名

发表评论

匿名网友

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

确定