io

io.Reader short reads, EOF versus ErrUnexpectedEOF, and Copy returning a nil error after a successful copy.

模块页正文目前为英文。

The io package defines Reader, Writer, and helpers that copy or combine them. Import it as "io". A Reader.Read may return fewer bytes than the length of the buffer without an error when that is all that is available. Callers must not assume that a successful Read fills p.

EOF is the error returned by Read when no more input is available. Official documentation requires Read to return EOF itself, not an error that only wraps EOF, because callers compare the error with ==. Helpers that are defined to read until EOF, including Copy and ReadAll, return a nil error on success, not EOF.

Examples were checked against Go 1.24.0. See the official package documentation for the complete API.

Go reference overview →

API index

APISummary
io.Reader.Read, io.EOFRead into a buffer. A successful read may be shorter than len(p). A later empty read can return EOF.
io.ReadFull, io.ErrUnexpectedEOFRead exactly len(buf) bytes. A short final read is ErrUnexpectedEOF, not a successful fill.
io.Copy, io.ReadAll, io.LimitReader, io.MultiReaderCopy until EOF, read all remaining bytes, cap a reader at n bytes, or concatenate readers.

Read, short reads, and EOF

strings.Reader typically returns the available data with a nil error, then a later Read returns 0 and EOF. That is allowed, but not required of every Reader: a Read may also return n > 0 together with an error, including EOF, and the caller should keep the data and then handle the error. The oneByte type below always returns a single byte, even when the caller passes a larger buffer, which is a short read without an error. ReadFull must fill the buffer. If it hits EOF after reading some but not all of the bytes, the error is ErrUnexpectedEOF. If no bytes were read, the error is EOF.

io.Reader.Read, io.EOF

type Reader interface {
	Read(p []byte) (n int, err error)
}
var EOF = errors.New("EOF")

Read into a buffer. A successful read may be shorter than len(p). A later empty read can return EOF.

ParameterDescription
pThe buffer to fill. n is the number of bytes placed in p, and only p[:n] is valid.

Returns: The number of bytes read and an error. 0 and EOF means there is no more input.

Errors

  • io.EOF — No more input is available. Compare this sentinel with ==, or with errors.Is. Do not wrap EOF when implementing Read.
  • This strings.Reader example returns 3, nil and then 0, EOF. Other readers may combine the last bytes and EOF in one call.
go
package main

import (
	"fmt"
	"strings"
)

func main() {
	r := strings.NewReader("abc")
	buf := make([]byte, 8)
	n, err := r.Read(buf)
	fmt.Printf("%d %v %q\n", n, err, buf[:n])
	n, err = r.Read(buf)
	fmt.Printf("%d %v\n", n, err)
}

Expected output

3 <nil> "abc"
0 EOF

Official documentation →

io.ReadFull, io.ErrUnexpectedEOF

func ReadFull(r Reader, buf []byte) (n int, err error)
var ErrUnexpectedEOF = errors.New("unexpected EOF")

Read exactly len(buf) bytes. A short final read is ErrUnexpectedEOF, not a successful fill.

ParameterDescription
rThe reader to consume. The example uses a Reader that returns at most one byte per call, so a 3-byte buffer is not filled in one Read.
bufReadFull must fill this entire buffer, issuing as many Read calls as needed.

Returns: n == len(buf) if and only if err == nil. If no bytes were read, the error is EOF. If some but not all bytes were read before EOF, the error is ErrUnexpectedEOF.

Errors

  • io.EOF — Returned by ReadFull only when no bytes were read.
  • io.ErrUnexpectedEOF — EOF occurred in the middle of filling a fixed-size buffer.
  • ReadAtLeast is the more general form and takes a minimum byte count. ReadFull is ReadAtLeast with min equal to len(buf).
go
package main

import (
	"fmt"
	"io"
)

type oneByte struct {
	s string
	i int
}

func (r *oneByte) Read(p []byte) (int, error) {
	if r.i >= len(r.s) {
		return 0, io.EOF
	}
	if len(p) == 0 {
		return 0, nil
	}
	p[0] = r.s[r.i]
	r.i++
	return 1, nil
}

func main() {
	r := &oneByte{s: "abcd"}
	buf := make([]byte, 3)
	n, err := r.Read(buf)
	fmt.Printf("%d %v %q\n", n, err, buf[:n])

	n, err = io.ReadFull(&oneByte{s: "ab"}, make([]byte, 4))
	fmt.Printf("%d %v\n", n, err)
	n, err = io.ReadFull(&oneByte{s: ""}, make([]byte, 4))
	fmt.Printf("%d %v\n", n, err)
}

Expected output

1 <nil> "a"
2 unexpected EOF
0 EOF

Official documentation →

Copy, LimitReader, and MultiReader

Copy reads from src until EOF or an error and writes to dst. A successful copy returns err == nil, not EOF, because reaching EOF is the defined end of the operation. If src implements WriterTo, Copy uses that; otherwise if dst implements ReaderFrom, Copy uses that. CopyN copies a fixed number of bytes and returns a nil error only when it wrote exactly n bytes. LimitReader stops with EOF after n bytes. MultiReader concatenates readers in order. ReadAll reads until an error or EOF and, like Copy, returns a nil error on success.

io.Copy, io.ReadAll, io.LimitReader, io.MultiReader

func Copy(dst Writer, src Reader) (written int64, err error)
func ReadAll(r Reader) ([]byte, error)
func LimitReader(r Reader, n int64) Reader
func MultiReader(readers ...Reader) Reader

Copy until EOF, read all remaining bytes, cap a reader at n bytes, or concatenate readers.

ParameterDescription
dst, src, rThe writer and reader for Copy, or the reader to drain or limit.
nLimitReader returns EOF after n bytes have been read from r.
readersMultiReader reads these inputs sequentially.

Returns: Copy returns the number of bytes written and the first copy error, or nil on success. ReadAll returns the collected bytes and a nil error on success. LimitReader and MultiReader return a Reader.

Errors

  • error — Copy and ReadAll do not report EOF as a failure. Any other read or write error is returned, including ErrShortWrite when a write accepts fewer bytes than requested without an explicit error.
  • The example writes to a bytes.Buffer and does not use the network or os.Stdout.
go
package main

import (
	"bytes"
	"fmt"
	"io"
	"strings"
)

func main() {
	var dst bytes.Buffer
	written, err := io.Copy(&dst, strings.NewReader("hello"))
	fmt.Printf("%d %v %q\n", written, err, dst.String())
	got, err := io.ReadAll(io.LimitReader(strings.NewReader("abcdef"), 3))
	fmt.Printf("%q %v\n", got, err)
	got, err = io.ReadAll(io.MultiReader(strings.NewReader("ab"), strings.NewReader("cd")))
	fmt.Printf("%q %v\n", got, err)
}

Expected output

5 <nil> "hello"
"abc" <nil>
"abcd" <nil>

Official documentation →