dongrang2140
2018-11-09 16:42
浏览 544
已采纳

为什么在golang中的类型错误下方出现此紧急示例?

Why is this panicf-sprintf causing a type error in Golang 1.11? Go doesn't explain the reason, even if it says this is a common mistake.

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

go vet is now enforced during the build.

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

The test is returning

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

vet describes this as

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"

Please help explain ... in golang in this context.

Here is a functional playground: https://play.golang.org/p/DijjanQNkxK

图片转代码服务由CSDN问答提供 功能建议

此panicf-sprintf为什么引起 type 错误 在Golang 1.11中? 即使它说这是一个常见的错误,Go也不解释原因。

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

go兽医现在在

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

测试返回

  missing ...在args中转发给类似printf的函数
   
 
 

vet 将此描述为

  func(* ptrStringer)BadWrap(x int,args ... interface {}  )string {
 return fmt.Sprint(args)//错误“在args中丢失了...转发给类似打印的函数” 
} 
 
func(* ptrStringer)BadWrapf(x int,格式为string,args。  ..interface {})字符串{
 return fmt.Sprintf(format,args)//错误“缺少...在args中被转发给类似printf的函数” 
   
 
  

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

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

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 邀请回答

1条回答 默认 最新

  • dthh5038 2018-11-09 16:47
    最佳回答

    panicf() accepts i as a variadic, the same as fmt.Sprintf(). Therefore you have to tell the compiler that you want each value of i to be sent to fmt.Sprintf() instead of sending the entire thing as a slice.

    So change the code to:

    func panicf(s string, i ...interface{}) { panic(fmt.Sprintf(s, i...)) }
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题