The ubiquitous io.Reader interface's Read method returns a (int,
error). Surprisingly (for programmers coming from other languages with
a built-in or idiomatic Result<T, E> type), it's possible for both
return values to be non-zero. There's (often overlooked??) commentary
in https://pkg.go.dev/io#Reader that says:

> Callers should always process the n > 0 bytes returned before considering the 
> error err.

So that (again, especially for programmers used to saying result? or
"try result" or similar Result<T, E> aware mechanisms in other
languages), the following Go code is incorrect:

n, err := r.Read(buffer, etc)
if err != nil {
  return err
}
doStuffWith(buffer[:n])

---

Do any of the early Gophers remember the motivations for designing
Read's semantics in that way? At the libc or syscall level (and my
reading of FD.Read in internal/poll/fd_unix.go), I don't think
read(fd, etc) can return both non-zero.

Is it just that, if you've got a buffer of some sort (including the
compress/* packages), it can be more efficient (1 Read call instead of
2) to return (positiveN, io.EOF)?

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/CAOeFMNW2QyVYUHDAOLNYOS3FoOEOxi-UE5jo_KEq4c2_UN6-ow%40mail.gmail.com.

Reply via email to