go - 格式错误。新

我想实现一个 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 call

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

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

https://stackoverflow.com/questions/26957910/

相关文章:

android - PhoneNumberFormattingTextWatcher 不工作

html - 如何使用 CSS 自动添加节号(1.2、3.4.1)?

regex - Powershell Parsing Help - 如何将文件夹名称列表输出到文本文

java - 如何用空格左填充整数?

python - 均匀地并排打印 2 个均匀填充的列表

python - 带有 float 的格式字符串中的千位分隔符

python - 在 python 日志记录中是否有一个格式化程序来截断字符串?

python - 格式正确的乘法表

javascript - moment.js - 更改已格式化的过去日期的格式

.net - 格式化 json 文档