Formatted Errors with fmt.Sprintf-Compatible Syntax
To provide a version of errors.New accepting fmt.Sprintf-like parameters, a custom function can be defined as follows:
<code class="go">func NewError(format string, a ...interface{}) error { return errors.New(fmt.Sprintf(format, a)) }</code>
However, this implementation encounters a problem where the variadic argument a is treated as a single array parameter, causing issues with formatting.
To resolve this, it is necessary to ensure that a is interpreted as a variable number of arguments. This can be achieved by utilizing the three-dots notation ..., ensuring that fmt.Sprintf is aware of the variadic nature of the a argument:
<code class="go">func NewError(format string, a ...interface{}) error { return errors.New(fmt.Sprintf(format, a...)) }</code>
By adding the three-dots to the a argument, the custom NewError function can now correctly format error messages using fmt.Sprintf-compatible syntax.
The above is the detailed content of How can I use fmt.Sprintf-compatible syntax with errors.New?. For more information, please follow other related articles on the PHP Chinese website!