Go: The io.Writer interface

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.

Example

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

For example, 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)
str := buf.String()) // str == "Size: 85 MB."

Optimizing 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.

Comments

Be the first to comment!