Home > Article > Backend Development > Why Does My fmt.Fprintf Wrapper Print Unexpected Output?
Variadic functions in Go accept a variable number of arguments, which are stored as a slice of the specified type. When calling a variadic function, it's essential to understand how arguments are passed.
Consider the following code that attempts to create a wrapper around fmt.Fprintf with variable-length arguments:
func Die(format string, args ...interface{}) { str := fmt.Sprintf(format, args) fmt.Fprintf(os.Stderr, "%v\n", str) os.Exit(1) }
When calling Die("foo"), the output contains the unexpected "%%!(EXTRA []interface {}=[])".
The issue arises from passing the args slice directly to fmt.Sprintf. To correctly pass arguments individually, the ellipsis operator ... must be used:
package main import ( "fmt" "os" ) func Die(format string, args ...interface{}) { str := fmt.Sprintf(format, args...) fmt.Fprintf(os.Stderr, "%v\n", str) os.Exit(1) } func main() { Die("foo") }
By using ..., each element of the args slice is passed as a separate argument to fmt.Sprintf, resolving the issue and producing the expected output:
foo
The above is the detailed content of Why Does My fmt.Fprintf Wrapper Print Unexpected Output?. For more information, please follow other related articles on the PHP Chinese website!