dongyuluan7494 2015-02-09 14:56
浏览 10
已采纳

错误是值(博客)-逻辑上是相同的吗?

I just read the blog written by Rob Pike. I have a small question regarding this and may be I can be wrong too but would still like to get feedback and understand properly the Go.

In the blog there was a snippet code (which actually was written by @jxck_)

_, err = fd.Write(p0[a:b])
if err != nil {
    return err
}
_, err = fd.Write(p1[c:d])
if err != nil {
    return err
}
_, err = fd.Write(p2[e:f])
if err != nil {
    return err
}
// and so on

a) As per my understanding the above code will return if error occurred at fd.Write(p0[a:b]), and will never execute fd.Write(p1[c:d]) , right?

And Rob suggested to write something like this

var err error
write := func(buf []byte) {
    if err != nil {
        return
    }
    _, err = w.Write(buf)
}
write(p0[a:b])
write(p1[c:d])
write(p2[e:f])
// and so on
if err != nil {
    return err
}

b) Based on the above, looks like the error will return from the sub function. So this means if the error occurs at write(p0[a:b]) then still it will execute write(p1[c:d]), right? So this means logically both are not same, right?

Anybody explain.

  • 写回答

2条回答 默认 最新

  • douxi5940 2015-02-09 15:00
    关注

    a) Yes, you are correct. If the error occures in the first write, it will return.

    b) No. The write in this example is a closure. The err inside of it is the same as in the outer scope. So if the first write fails, the other will simply return, because the outer err is not nil anymore.

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

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?