go 中的许多函数返回错误以适应接口(interface),但这些错误始终为 nil。是否仍应检查这些错误?
一个例子是 crypto/sha1 Write() function ,它不设置错误值。所以代码不需要是:
_, err = sha1Hasher.Write(buffer)
if err != nil {
log.Printf("sha1 could not be calculated (%s)", err)
}
但仅:
sha1Hasher.Write(buffer)
第二个选项更短更简洁,go 中有很多关于简单代码的内容,但建议处理所有错误:
But remember: Whatever you do, always check your errors!
https://blog.golang.org/errors-are-values
Clearly, we must handle any errors; we can't just ignore them.
https://stackoverflow.com/a/16126516/4944254
哪种方式最好?
最佳答案
在您描述的情况下,不检查错误可能会很好,就像使用 fmt.Println
时不检查错误一样。 .
但是,当您使用 fmt.Println
您知道正在使用哪些具体实现。当您使用 Writer
时接口(interface)(os.Stdout
实现)——你不能假设实现是否会返回任何错误。在那种情况下,恕我直言,您应该始终检查错误。
顺便说一句,写信给os.Stdout
,这fmt.Print
使用,可能会失败(可以将 os.Stdout
的值替换为其他值)。
关于go - 去处理所有返回的错误是惯用的吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40142060/