如何修复 linter 警告“未检查错误返回值”?

Evg*_*lyy 6 go linter

我正在调用具有错误类型值的方法(代码示例中的 foo())。我不在乎这个结果。什么是正确的代码风格编写方式?Errcheck linter 让我检查这个错误。

//for example, same method may be called from imported entity
func foo() error {
   if err := someFunction(); err != nil {
       return err
   }
   return nil
}

func process() {
   //linter doesn't like this
   foo()

   //this way leads to unused variable error
   err := foo()

   //is this clean way?
   _ = foo()

  return 
}
Run Code Online (Sandbox Code Playgroud)

apx*_*pxp 9

这是惯用的方式:

err := foo()
if err != nil {
  // handle your error here
}
Run Code Online (Sandbox Code Playgroud)

您不应该忽略可能的错误。将其记录或打印到标准输出,但不要忽略它。


Ser*_*sev 5

是的,将它分配给通配符变量是忽略错误的好方法。但是强烈反对整个做法(忽略错误)。以下是“Effective Go”对此的看法:

有时,您会看到为了忽略错误而丢弃错误值的代码;这是可怕的做法。始终检查错误返回;提供它们是有原因的。

   // Bad! This code will crash if path does not exist.
    fi, _ := os.Stat(path)
    if fi.IsDir() {
        fmt.Printf("%s is a directory\n", path)
    }
Run Code Online (Sandbox Code Playgroud)