"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > 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?

Published on 2024-11-09
Browse:649

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))
}

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.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3