Home > Backend Development > Golang > How to Pass Variable Arguments to `fmt.Sprintf` in a Custom `errors.New` Implementation?

How to Pass Variable Arguments to `fmt.Sprintf` in a Custom `errors.New` Implementation?

Mary-Kate Olsen
Release: 2024-11-05 00:16:02
Original
406 people have browsed it

How to Pass Variable Arguments to `fmt.Sprintf` in a Custom `errors.New` Implementation?

How to Implement a Version of errors.New That Accepts the Same Parameters as fmt.Sprintf

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

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...))
}
Copy after login

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!

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