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
Release: 2024-11-05 06:00:03
Original
870 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template