“err declared but not used” with multiple errors “err声明但未使用”有多个错误

huangapple go评论86阅读模式
英文:

"err declared but not used" with multiple errors

问题

如果我有这样一个程序:

package main
import "strconv"

func main() {
   a, err := strconv.Atoi("100")
   println(a)
}

我得到了预期的结果:

.\file.go:5:7: err declared but not used

然而,这个程序:

package main
import "strconv"

func main() {
   a, err := strconv.Atoi("100")
   if err != nil {
      panic(err)
   }
   b, err := strconv.Atoi("100")
   println(a, b)
}

编译时没有错误,即使我从未检查过第二个 err 值。为什么会这样?另外,我能改变一些选项,使得这些错误导致编译时的错误或警告吗?

英文:

If I have a program like this:

package main
import "strconv"

func main() {
   a, err := strconv.Atoi("100")
   println(a)
}

I get this result, as expected:

.\file.go:5:7: err declared but not used

However this program:

package main
import "strconv"

func main() {
   a, err := strconv.Atoi("100")
   if err != nil {
      panic(err)
   }
   b, err := strconv.Atoi("100")
   println(a, b)
}

Compiles without error, even though I never checked the second err value. Why does this happen? Also, can I change some option, so that these mistakes result in compile time errors or warnings?

答案1

得分: 4

这是因为在第二种情况下,您正在重复使用现有的 err 变量,所以它被使用了。尽管使用了 := 实例化和赋值运算符,但并没有实例化一个新的 err 变量。

如果您将错误命名为不同的变量,例如:

func main() {
   a, err := strconv.Atoi("100")
   if err != nil {
      panic(err)
   }
   b, err2 := strconv.Atoi("100")
   println(a, b)
}

那么您将在两种情况下都会看到编译错误。

如果您不想更改代码但仍然希望收到此问题的通知,您将需要依赖于 Go 语言的一个 linter 而不是 Go 编译器。Go 有一个非常强大的 linter 生态系统,所以我不会推荐特定的一个,但在我们的组织中,如果我编写了这样的代码,我们的 linter 将会显示类似于以下错误:

scratch/test.go:10:2: ineffectual assignment to err (ineffassign)
           b, err := strconv.Atoi("100")
英文:

This is because in the second case you are re-using an existing err variable, so it is being used. Despite the := instantiate & assign operator, a new err variable is not instantiated.

If you named the errors differently, such as this:

func main() {
   a, err := strconv.Atoi("100")
   if err != nil {
      panic(err)
   }
   b, err2 := strconv.Atoi("100")
   println(a, b)
}

Then you would see a compile error for both cases.

If you don't want to change your code but also still want to be notified of this issue, you will need to rely on a go linter instead of the go compiler. Go has a very robust ecosystem of linters so I won't recommend one in particular, but at my organization I would see an error like this from our linter if I were to write such code:

scratch/test.go:10:2: ineffectual assignment to err (ineffassign)
           b, err := strconv.Atoi("100")

huangapple
  • 本文由 发表于 2021年6月9日 04:34:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/67894237.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定