How to use the io.Writer interface

yourbasic.org/golang

Basics

The io.Writer interface represents an entity to which you can write a stream of bytes.

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

Write writes up to len(p) bytes from p to the underlying data stream – it returns the number of bytes written and any error encountered that caused the write to stop early.

The standard library provides many Writer implementations, and Writers are accepted as input by many utilities.

Use a built-in writer

Since bytes.Buffer has a Write method you can write directly into the buffer using fmt.Fprintf.

var buf bytes.Buffer
fmt.Fprintf(&buf, "Size: %d MB.", 85)
s := buf.String()) // s == "Size: 85 MB."

Optimize string writes

Some Writers in the standard library have an additional WriteString method. This method can be more efficient than the standard Write method since it writes a string directly without allocating a byte slice.

You can take direct advantage of this optimization by using the io.WriteString() function.

func WriteString(w Writer, s string) (n int, err error)

If w implements a WriteString method, it is invoked directly. Otherwise, w.Write is called exactly once.

Share this page: