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?
Variadic functions receive the arguments as a slice of the type. In this case your function receives a
[]interface{}namedargs. When you pass that argument tofmt.Sprintf, you are passing it as a single argument of type[]interface{}. What you really want is to pass each value inargsas a separate argument (the same way you received them). To do this you must use the...syntax.This is also explained in the Go specification here.