Home > Article > Backend Development > Why does "foo%!(EXTRA []interface {}=[])" appear when calling a `fmt.Fprintf` wrapper with variadic arguments?
Variadic Function Argument Pass-Through Issue in fmt.Fprintf Wrapper
This article addresses an issue encountered when creating a simple fmt.Fprintf wrapper that accepts a variable number of arguments.
Problem: Incorrect Output When Calling Wrapper
When calling the wrapper function Die("foo"), an unexpected output is produced: "foo%!(EXTRA []interface {}=[])". This raises two questions:
Solution: Using Spread Operator
Variadic functions in Go receive arguments as a slice. In this case, the wrapper function Die has a parameter args of type []interface{}. However, when passing this argument to fmt.Sprintf, it is treated as a single argument of type []interface{}.
To resolve this issue and pass each value in args as a separate argument, the spread operator (...) must be used. By adding this syntax to the fmt.Sprintf call, the individual values in args are expanded and passed accordingly:
str := fmt.Sprintf(format, args...)
This approach ensures that the wrapper function correctly passes the variable arguments to fmt.Fprintf.
The above is the detailed content of Why does "foo%!(EXTRA []interface {}=[])" appear when calling a `fmt.Fprintf` wrapper with variadic arguments?. For more information, please follow other related articles on the PHP Chinese website!