【问题标题】:Why is this panic example below a type error in golang?为什么这个恐慌示例在 golang 中的类型错误下方?
【发布时间】:2019-04-13 06:29:29
【问题描述】:

为什么这个 panicf-sprintf 在 Golang 1.11 中会导致 type 错误? Go 没有解释原因,即使它说这是一个常见错误。

https://golang.org/doc/go1.11#vet

go vet 现在在构建期间强制执行。

func panicf(s string, i ...interface{}) { panic(fmt.Sprintf(s, i)) }

测试返回

missing ... in args forwarded to printf-like function

vet 将其描述为

func (*ptrStringer) BadWrap(x int, args ...interface{}) string {
    return fmt.Sprint(args) // ERROR "missing ... in args forwarded to print-like function"
}

func (*ptrStringer) BadWrapf(x int, format string, args ...interface{}) string {
    return fmt.Sprintf(format, args) // ERROR "missing ... in args forwarded to printf-like function"

请在这种情况下帮助解释 golang 中的...

这是一个功能性游乐场:https://play.golang.org/p/DijjanQNkxK

【问题讨论】:

标签: go types


【解决方案1】:

panicf() 接受i 作为可变参数,与fmt.Sprintf() 相同。因此,您必须告诉编译器您希望将 i 的每个值发送到 fmt.Sprintf(),而不是将整个内容作为切片发送。

所以把代码改成:

func panicf(s string, i ...interface{}) { panic(fmt.Sprintf(s, i...)) }

【讨论】:

    猜你喜欢
    • 2015-03-29
    • 2013-03-31
    • 2017-05-07
    • 2021-09-21
    • 2014-09-21
    • 2020-10-23
    • 1970-01-01
    • 1970-01-01
    • 2015-09-28
    相关资源
    最近更新 更多