Readers

The io package specifies the io.Reader interface, which represents the read end of a stream of data.

The Go standard library contains many implementations of these interfaces, including files, network connections, compressors, ciphers, and others.

The io.Reader interface has a Read method:

  1. func (T) Read(b []byte) (n int, err error)

Read populates the given byte slice with data and returns the number of bytes populated and an error value. It returns an io.EOF error when the stream ends.

The example code creates a strings.Reader and consumes its output 8 bytes at a time.

reader.go

  1. package main
  2. import (
  3. "fmt"
  4. "io"
  5. "strings"
  6. )
  7. func main() {
  8. r := strings.NewReader("Hello, Reader!")
  9. b := make([]byte, 8)
  10. for {
  11. n, err := r.Read(b)
  12. fmt.Printf("n = %v err = %v b = %v\n", n, err, b)
  13. fmt.Printf("b[:n] = %q\n", b[:n])
  14. if err == io.EOF {
  15. break
  16. }
  17. }
  18. }