我正在调用错误类型值的方法(代码示例中的 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
}
最佳答案
是的,将其分配给通配符变量是忽略错误的好方法。但强烈反对整个做法(忽略错误)。以下是“Effective Go”对此的评价:
Occasionally you'll see code that discards the error value in order to ignore the error; this is terrible practice. Always check error returns; they're provided for a reason.
// 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) }
关于go - 如何修复 linter 警告 `Error return value is not checked`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691931/