Read with io.Reader and handle partial results
Read with io.Reader and handle partial results
An io.Reader supplies bytes through Read(p []byte) (n int, err error). The caller owns the buffer p and uses only p[:n]. A successful read need not fill the buffer. A reader may return useful bytes and an error in the same call, so process the bytes before handling the error.
package main
import ( "fmt" "io" "strings")
func main() { var r io.Reader = strings.NewReader("hello") p := make([]byte, 3) for { n, err := r.Read(p) if n > 0 { fmt.Println(string(p[:n])) } if err == io.EOF { break } if err != nil { fmt.Println(err) break } }}The final short read contains only two bytes. Reading the entire buffer would include stale data. A subsequent EOF ends this stream. A return of 0,nil does not mean EOF; a general loop may need a no-progress policy for misbehaving readers.
Expected output:
helloHandle bytes and EOF together
package main
import ( "fmt" "io")
type last struct{ done bool }
func (r *last) Read(p []byte) (int, error) { if len(p) == 0 { return 0, nil } if r.done { return 0, io.EOF } r.done = true p[0] = 'X' return 1, io.EOF}func main() { r := &last{} p := make([]byte, 4) n, err := r.Read(p) fmt.Println(string(p[:n]), err == io.EOF)}This test reader returns one byte with EOF. Checking EOF before consuming n would lose X. Read implementations must not retain the supplied buffer. Use io.ReadFull when a protocol requires exactly a fixed number of bytes; it reports io.ErrUnexpectedEOF after a partial read at EOF.
Expected output:
X trueTry it locally
Read exactly three bytes from "abcd" and from "ab" using io.ReadFull. Print the bytes actually read and whether an error occurred.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
I/O contracts 01: Read with io.Reader and handle partial results
Check the lesson objective before moving on.
A Read call returns n=2 and io.EOF. What should you do?
What does 0,nil from Read mean?