CodeBlanks Logo Icon CodeBlanks

Summary - io package

Combine Reader and Writer to write a file copier.

io package summary

I/O in Go is built on two small interfaces: io.Reader and io.Writer. Functions that accept them work the same with files, networks, memory and HTTP, and are easy to test. Your toolbox: io.ReadAll, io.Copy, io.LimitReader, io.TeeReader, io.MultiWriter, bufio.Scanner, bufio.Writer.

Rule: for large data, don't read it all — stream it.

Your own Reader

Implementing the interface is easy. A Reader wrapper that upper-cases every letter:

type buyukReader struct{ r io.Reader }

func (b buyukReader) Read(p []byte) (int, error) {
    n, err := b.r.Read(p)
    copy(p, bytes.ToUpper(p[:n]))
    return n, err
}

This wrapper works directly with io.Copy, bufio.Scanner and every other tool.

Practice Wrapper Reader

Write the buyukReader above and run it with io.Copy(os.Stdout, buyukReader{strings.NewReader("gopher\n")}).

Starter code

main.go
package main

import (
    "bytes"
    "io"
    "os"
    "strings"
)

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import (
    "bytes"
    "io"
    "os"
    "strings"
)

type buyukReader struct{ r io.Reader }

func (b buyukReader) Read(p []byte) (int, error) {
    n, err := b.r.Read(p)
    copy(p, bytes.ToUpper(p[:n]))
    return n, err
}

func main() {
    io.Copy(os.Stdout, buyukReader{strings.NewReader("gopher\n")})
}

Expected output

GOPHER

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What happens if you use <code>bufio.NewWriter</code> and don't call <code>Flush</code>?

  • It has no effect
  • The last data in the buffer is never written Correct answer
  • The program crashes
  • The data is written twice

Explanation: bufio.Writer keeps data in memory until 4 KB fills; Flush sends the remaining bytes to the underlying Writer.

2 Flush the buffer

Question
w := bufio.NewWriter(os.Stdout)
fmt.Fprintln(w, "son satır")
w.____()
Answer
w := bufio.NewWriter(os.Stdout)
fmt.Fprintln(w, "son satır")
w.Flush()

Explanation: Flush writes the bytes waiting in the buffer to the underlying Writer.

3 Group summary

Term Meaning
io.Reader Read(p []byte)
io.Writer Write(p []byte)
bufio.Scanner Line-by-line reading
io.Copy Streaming transfer

All lessons in Intermediate