我正在使用错误类型值(代码示例中的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
}
答案 0 :(得分:2)
是的,将其分配给通配符变量将是忽略该错误的好方法。但是强烈建议不要忽略(忽略错误)整个实践。这是“ 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) }
答案 1 :(得分:1)
这是惯用的方式:
err := foo()
if err != nil {
// handle your error here
}
您不应忽略可能的错误。记录或打印到标准输出,但不要忽略它。
答案 2 :(得分:0)