Skip to content

proposal: io: require io.Reader to return either n > 0 or an error #27531

Closed
@crawshaw

Description

@crawshaw

Today the Read method of an io.Reader is allowed to return 0, nil. It is uncommon and discouraged:

Implementations of Read are discouraged from returning a zero byte
count with a nil error, except when len(p) == 0. Callers should treat a
return of 0 and nil as indicating that nothing happened; in particular
it does not indicate EOF.

It is so uncommon that it is hard to remember to deal with this case when using an io.Reader. All correct calls to Read need to be wrapped in a loop that tries multiple times, and after some ill-defined cutoff, report an error like io.ErrNoProgress. Consider the correct example of reading from bufio.Reader:

// Read new data: try a limited number of times.
for i := maxConsecutiveEmptyReads; i > 0; i-- {
	n, err := b.rd.Read(b.buf[b.w:])
	if n < 0 {
		panic(errNegativeRead)
	}
	b.w += n
	if err != nil {
		b.err = err
		return
	}
	if n > 0 {
		return
	}
}
b.err = io.ErrNoProgress

For Go 2 I propose we change the contract of io.Reader so implementations are required to return either n > 0 or a non-nil error.

Metadata

Metadata

Assignees

No one assigned

    Labels

    FrozenDueToAgeNeedsInvestigationSomeone must examine and confirm this is a valid issue and not a duplicate of an existing one.Proposal

    Type

    No type

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions