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.
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.
No, they are the same. If an error
occurs at fd.Write(p0[a:b])
, the err
variable will hold its value.
Now if you call write(p1[c:d])
, then the write()
func will first check if err != nil
but since it already stores the error
which occured in the previous call, it will return immediately and will not execute further code.