2 ms·
As an aside, there is a notable Go API that a lot of people get wrong: io.Reader's Read() and io.Writer's Write() both return a count when they return io.EOF, a
by atombender 8y ago
As an aside, there is a notable Go API that a lot of people get wrong: io.Reader's Read() and io.Writer's Write() both return a count when they return io.EOF, and if the count is a positive number, the buffer was filled.
If you do a code search for Go projects on Github, a disturbing number of them get this utterly wrong, and simply do something like this:
for {
c, err := r.Read(buf)
if err == io.EOF {
break
}
if err != nil {
return err
}
...
When they should be doing something like:
for {
c, err := r.Read(buf)
if err == io.EOF {
if c == 0 {
break
}
} else if err != nil {
return err
}
This is an unfortunate API design, because almost all error-returning functions have disjoint return values, and would could be expressed as sum types in other languages, which teaches developers to not expect both return values to be valid at the same time. It certainly surprised me.
The other problem with Go's design is that you have to read the documentation to understand what the semantics of a particular function are. The type system can't tell you.