我想实现一个 errors.New
版本,它接受与 fmt.Sprintf
相同的参数为此,我编写了以下函数:
func NewError(format string, a ...interface{}) error {
return errors.New(fmt.Sprintf(format, a))
}
然而,a
成为 NewError()
内的单个数组参数,从而导致 Sprintf()
在格式字符串。如何强制将 a
解释为可变数量的参数?
最佳答案
fmt.Errorf
已经做了你想做的事。看its source ,您可以看到出了什么问题:
// 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...))
}
请注意,您的代码在 a
之后缺少 ...
。来自 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 calls := []string{"James", "Jasmine"} Greeting("goodbye:", s...)
within
Greeting
, who will have the same value ass
with the same underlying array.
https://stackoverflow.com/questions/26957910/