英文:
Formatted errors.New
问题
我想实现一个与fmt.Sprintf接受相同参数的errors.New版本。为此,我编写了以下函数:
func NewError(format string, a ...interface{}) error {
return errors.New(fmt.Sprintf(format, a))
}
然而,在NewError()内部,a变成了一个单一的数组参数,导致Sprintf()只填充了格式字符串中的一个参数。我该如何强制a被解释为可变数量的参数?
英文:
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?
答案1
得分: 28
fmt.Errorf 已经实现了你想要做的功能。从它的源代码可以看出你的问题所在:
// Errorf 根据格式说明符进行格式化,并返回满足 error 接口的字符串值。
func Errorf(format string, a ...interface{}) error {
return errors.New(Sprintf(format, a...))
}
注意,在 a 后面缺少了 ...。根据规范:
> ### 将参数传递给 ... 参数
>
> 如果最后一个参数可以赋值给切片类型 []T,并且在参数后面跟着 ...,那么它可以不变地作为 ...T 参数的值传递。在这种情况下,不会创建新的切片。
>
> 给定切片 s 和调用
>
> s := []string{"James", "Jasmine"}
> Greeting("goodbye:", s...)
>
> 在 Greeting 函数内部,s 将具有与原始切片相同的值和底层数组。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论