Go encourages to handle errors at the place where they're reported.
However, if the io.Reader.Read is defined to be free to return valid,
non zero length data _and_ a non nil error in the same time then the
correct client behavior is to consume the valid data first.
n, err := r.Read(b)
if n > 0 {
// consume b[:n]
}
if err != nil {
// handle err, probably treating io.EOF specially
}
Also, it's easy to wrap any io.Reader in a way where the "outer"
Reader will never return non zero n && non nil error while preserving
the correct semantics.
I'm still having question why go had allow this.
--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
http://godoc.org/archive/tar#Reader.Next
"Read reads from the current entry in the tar archive. It returns 0, io.EOF when it reaches the end of that entry, until Next is called to advance to the next entry."
I wouldn't be surprised if a large percent of non-stdlib Reader consumers get the pattern wrong. As mattn says, this case is different from every other Go API, so the muscle memory may overpower the details in the spec, and depending on answer to above question, it seems like other stdlib reader-ish things do not behave similarly.
Would checking for this mistaken usage be reasonable to add to "go vet" ? Perhaps vet could alert on the following case, which seems likely to be the most common incorrect usage pattern:
_, err := r.Read(b)
if err == io.EOF {
break
}
...
Not sure if that's within the scope of "go vet", or if it has the requisite type information.