Alex G.
Alex G.

Reputation: 2153

Formatted errors.New

I would like to implement a version of errors.New that accepts the same parameters as fmt.Sprintf To do so I wrote the following function:

func NewError(format string, a ...interface{}) error {
    return errors.New(fmt.Sprintf(format, a))
}

However, a becomes a single array parameter inside NewError() thereby causing Sprintf() to fill out just a single parameter in the format string. How can I force a to be interpreted as a variable number of arguments?

Upvotes: 17

Views: 13677

Answers (1)

user142162
user142162

Reputation:

fmt.Errorf already does what you are trying to do. Looking at its source, you can see what went wrong:

// Errorf formats according to a format specifier and returns the string
// as a value that satisfies error.
func Errorf(format string, a ...interface{}) error {
        return errors.New(Sprintf(format, a...))
}

Note your code is missing the ... after a. From the spec:

Passing arguments to ... parameters

If the final argument is assignable to a slice type []T, it may be passed unchanged as the value for a ...T parameter if the argument is followed by .... In this case no new slice is created.

Given the slice s and call

s := []string{"James", "Jasmine"}
Greeting("goodbye:", s...)

within Greeting, who will have the same value as s with the same underlying array.

Upvotes: 32

Related Questions