格式化错误.新 [英] Formatted errors.New
问题描述
我想实现一个errors.New
版本,该版本接受与fmt.Sprintf
相同的参数.为此,我编写了以下函数:
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))
}
但是,a
成为NewError()
内部的单个数组参数,从而导致Sprintf()
仅填写格式字符串中的单个参数.如何强制将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?
推荐答案
fmt.Errorf
已经做了什么您正在尝试做.查看其来源,您可以查看出了什么问题:
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...))
}
请注意,您的代码在a
之后缺少...
.从规范:
Note your code is missing the ...
after a
. From the spec:
将参数传递给...参数
如果最终参数可分配给切片类型
[]T
,则在参数后跟...
的情况下,可以将其不变地作为...T
参数的值传递.在这种情况下,不会创建新的切片.
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.
给出切片s
并调用
s := []string{"James", "Jasmine"}
Greeting("goodbye:", s...)
在Greeting
内,其值与s
相同,且具有相同的基础数组.
within Greeting
, who will have the same value as s
with the same underlying array.
这篇关于格式化错误.新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!