gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:30:59 28 4
gpt4 key购买 nike

调用 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 编译器来说,捕捉字符串格式化类型错误似乎并不比任何其他类型的错误更难。

最佳答案

你可以告诉 go vet 要检查哪些函数(比较 godoc.org/cmd/vet ):

$ cat x.go
package main

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 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

关于go - 如何检查 errors.Errorf() 中的类型错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51933966/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com