To implement a version of errors.New that accepts the same parameters as fmt.Sprintf, one can use the NewError function, which is defined as follows:
func NewError(format string, a ...interface{}) error { return errors.New(fmt.Sprintf(format, a)) }
However, this function does not work correctly because the variable number of arguments in a becomes a single array parameter in NewError, causing Sprintf to fill out only a single parameter in the format string.
To fix this issue, the final parameter in NewError should be marked as a variable number of arguments with the ... syntax:
func NewError(format string, a ...interface{}) error { return errors.New(fmt.Sprintf(format, a...)) }
This allows fmt.Sprintf to interpret a as variable number of arguments.
The above is the detailed content of How to Pass Variable Arguments to `fmt.Sprintf` in a Custom `errors.New` Implementation?. For more information, please follow other related articles on the PHP Chinese website!