doushizhou4477 2016-10-19 21:47
浏览 25
已采纳

去处理所有返回的错误是否很习惯?

Many functions in go return errors to fit an interface, but these errors are always nil. Should these errors still be checked?

An example for this is the crypto/sha1 Write() function, which does not set the err value. So the code does not need to be:

_, err = sha1Hasher.Write(buffer)
if err != nil {
    log.Printf("sha1 could not be calculated (%s)", err)
}

but only:

sha1Hasher.Write(buffer)

The second option is shorter and cleaner and go is a lot about simple code but it is suggested to handle all errors:

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

Which is the best way to go?

  • 写回答

1条回答 默认 最新

  • dqbhdsec59405 2016-10-19 23:14
    关注

    In situation that you described, you will probably be fine with not checking error, same as not checking errors when using fmt.Println.

    However, when you use fmt.Println you know which concrete implementations are being used. When you are using Writer interface (which os.Stdout implements) - you can not assume if implementation will return any errors. In that case, IMHO, you should always check errors.

    Btw, writing to os.Stdout, which fmt.Print uses, can fail (one might be able to replace value of os.Stdout to something else).

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答