如何检查 errors.Errorf() 中的类型错误?

调用 fmt.Printf 等字符串格式化函数似乎是 Go 编译器的弱点。我最终遇到了很多错误(重构后使用了错误的格式化程序,忘记包含所有参数),这些错误只会在运行时显示出来。因此,每次写其中一个时,我最终都不得不眯着眼睛。


我今天做了一些研究并发现go tool vet,它似乎适用于 fmt.Printf,但它不会捕获 errors.Errorf 中的错误(见下文)。


import "github.com/pkg/errors"


func ReturnError(s string, i int) error {

    // Swap %d and %s, and forget to include the second argument

    return errors.Errorf("invalid arguments %d and %s", s)

}

是否有类似的东西go tool vet可以捕获 errors.Errorf() 中的字符串格式错误?另外,根据我自己的理解,为什么这是一个如此困难的问题?对于 Go 编译器来说,捕捉字符串格式化类型错误似乎并不比任何其他类型的错误更难。


暮色呼如
浏览 99回答 1
1回答

米琪卡哇伊

您可以知道go vet要检查哪些功能(比较godoc.org/cmd/vet):$ cat x.gopackage mainimport "github.com/pkg/errors"func ReturnError(s string, i int) error {    // Swap %d and %s, and forget to include the second argument    return errors.Errorf("invalid arguments %d and %s", s)}$ go vet x.go $ go vet -printfuncs Errorf x.go # command-line-arguments./x.go:7: Errorf format %d has arg s of wrong type string由于多种原因,要更好地做到这一点并不简单:格式字符串是运行时值:您可能会调用fmt.Sprintf(prefix + "%s", ...). 所以不可能在编译时捕获所有无效的格式字符串。格式字符串没有特殊类型。因此,编译器无法通过查看函数定义轻松确定某个函数(errors.Errorf在本例中)期望其参数的行为与fmt.Printf函数定义相同。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go