×

go · level 2 · unit 3 · lesson 3

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

An is anywhere that text can go.

io.Writer is an interface from the io toolbox. Anything with the right Write method satisfies it: the screen, a file, a reply to a web browser. You rarely call Write yourself, because fmt does it for you.

works like Println, but writes to w, any writer you choose. fmt.Fprintf does the same for Printf. os.Stdout is the screen, so fmt.Fprintln(os.Stdout, "Hi") prints as usual.

A is a writer that collects text instead of showing it. Its Write method has a pointer receiver, so hand over its address: fmt.Fprintf(&b, ...). Then b.String() gives back everything written.

package main
import "fmt"
import "io"
import "os"
import "strings"
func receipt(w io.Writer, item string, price int) {
	fmt.Fprintf(w, "%v: £%v\n", item, price)
}
func main() {
	receipt(os.Stdout, "tea", 2)
	var b strings.Builder
	receipt(&b, "cake", 3)
	receipt(&b, "toast", 1)
	fmt.Print("Saved for later:\n", b.String())
}

Later you will hand a writer to a web server, and the same fmt.Fprintf will write the reply.