dtutlamjasblef7982 2015-06-24 13:12
浏览 183
已采纳

如何忽略GO中返回的错误

I have started learning Go today.
One thing that makes me crazy, it's the err returned parameter.

Let's assume I need to nest few functions. like this:

return string(json.Marshal(MyData))

or more complex example:

return func1(func2(func3(MyData)))

Is it really necessary to write:

tmp1 , _ = func3(MyData)
tmp2 , _ = func2(tmp1)
tmp3 , _ = func1(tmp2)
return tmp3

That's annoying!
Is there any way to make the code looks cleaner?

  • 写回答

3条回答 默认 最新

  • dtc4547 2015-06-24 13:44
    关注

    The real answer is: Don't.

    Never just ignore the errors.

    Seriously. The errors are there for a reason. If a function returns an error, it almost always means that it's possible, during the operation of your program, even if it's 100% bug-free, for the function to fail. And if it does, you don't usually want to just keep going as if nothing happened.

    If you're absolutely sure that you're using a function in a way that ensures that it will never return a non-nil error (unless there's a bug in your program, and there always is), you might want to write a Must-style function like in the template package which panics with the returned error value.

    Error handling is not noise. It's not clutter. It's not something you want to get rid of. If it looks like 50% of your program is error handling, that's because 50% of your program is, and should be, error handling.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图
  • ¥15 对接wps接口实现获取元数据
  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?