Home >Backend Development >Golang >How can I use fmt.Sprintf-compatible syntax with errors.New?

How can I use fmt.Sprintf-compatible syntax with errors.New?

Barbara Streisand
Barbara StreisandOriginal
2024-11-05 06:00:03865browse

How can I use fmt.Sprintf-compatible syntax with errors.New?

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn