Skip to content

Write Through io.Writer

The Course
•
25 min study

A function that calls fmt.Println decides for itself that its output goes to the terminal. That is fine until you want to check the output from code, send it to a file, or show it somewhere else: the function has to change every time. io.Writer lets the caller decide instead. It is a one-method interface from the standard library:

Go
type Writer interface {
	Write(p []byte) (n int, err error)
}

Anything with that method accepts bytes. A *strings.Builder collects them into a string you can inspect, and os.Stdout sends them to the terminal. fmt.Fprintln and fmt.Fprintf work like Println and Printf but take a writer as their first argument, and return the byte count and an error.

Predict and run

Does report print directly to the console?

Predict, then run Go
package main

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

func report(w io.Writer, count int) error {
	_, err := fmt.Fprintln(w, "Open tasks:", count)
	return err
}

func main() {
	var output strings.Builder
	if err := report(&output, 2); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%q\n", output.String())
}
Check your prediction
Text
"Open tasks: 2\n"

Nothing reaches the terminal until main prints what the builder captured. %q shows the text with its line ending, which a plain Println would hide. The & in report(&output, 2) is the method-set rule from the last lesson: Write has a pointer receiver.

One function, two destinations

Because report asks only for an io.Writer, the same code serves a check and the real program:

Capture, then print Go
package main

import (
	"fmt"
	"io"
	"os"
	"strings"
)

func report(w io.Writer, count int) error {
	_, err := fmt.Fprintln(w, "Open tasks:", count)
	return err
}

func main() {
	var output strings.Builder
	report(&output, 2)
	fmt.Println(output.String() == "Open tasks: 2\n")
	report(os.Stdout, 3)
}
Text
true
Open tasks: 3

The first call writes into the builder, and the comparison checks it. The second writes straight to the terminal. The Day 7 queue's run takes a writer for the same reason: main passes os.Stdout, and the checks pass a builder. (This example ignores report's error to keep it short. The next playground shows how to handle it.)

Find the bug

This check should pass: summary writes one line and the check compares it. Instead, the line appears in the output and the check fails. Find out why before you open the hint.

Find the bug Go
package main

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

func summary(w io.Writer, done, open int) error {
	_, err := fmt.Println("Done:", done, "Open:", open)
	return err
}

func main() {
	var out strings.Builder
	if err := summary(&out, 2, 1); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(out.String() == "Done: 2 Open: 1\n")
}
Text
Done: 2 Open: 1
false
Check your fix

summary accepts w and then ignores it: fmt.Println always writes to standard output. Write to the writer it was given:

Fixed Go
package main

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

func summary(w io.Writer, done, open int) error {
	_, err := fmt.Fprintln(w, "Done:", done, "Open:", open)
	return err
}

func main() {
	var out strings.Builder
	if err := summary(&out, 2, 1); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Println(out.String() == "Done: 2 Open: 1\n")
}
Text
true

The clue was output appearing before main printed anything: a function that is supposed to write to its writer should never show up in the terminal on its own.

Practice

Exercise

Your turn

Write writeList(w io.Writer, titles []string) error, which writes a heading Tasks: and then each title on its own line, numbered from 1. Stop at the first failed write and return its error. Capture the list for Read and Draft in a strings.Builder, then print it with %q. The output should be:

Text
"Tasks:\n1. Read\n2. Draft\n"
Your working space Go
package main

import (
	"fmt"
)

func main() {
	titles := []string{"Read", "Draft"}
	fmt.Println(titles)
}
Hint 1: the idea

Every Fprintln or Fprintf returns an error, and the function should return the first one it meets. The caller decides where the text goes by passing the writer.

Hint 2: a first step

Write the heading with fmt.Fprintln(w, "Tasks:") and return its error if it is not nil. Call writeList(&out, titles) and print %q of out.String(): you should see "Tasks:\n". Then add the loop with Fprintf and %d. %s\n.

Worked solution
Run the solution Go
package main

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

func writeList(w io.Writer, titles []string) error {
	if _, err := fmt.Fprintln(w, "Tasks:"); err != nil {
		return err
	}
	for i, title := range titles {
		if _, err := fmt.Fprintf(w, "%d. %s\n", i+1, title); err != nil {
			return err
		}
	}
	return nil
}

func main() {
	titles := []string{"Read", "Draft"}
	var out strings.Builder
	if err := writeList(&out, titles); err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("%q\n", out.String())
}
Text
"Tasks:\n1. Read\n2. Draft\n"

Each write is checked, so a destination that fails halfway, such as a full disk, stops the list and tells the caller. The queue's report has the same shape. Day 6 builds a writer that fails on purpose to prove the check works.

Was this article helpful?

Your response is saved on this device.