Skip to content
Tutorials Center
My learning

Topics

Lesson 52 of 147 ยท Interfaces

Common Standard Interfaces

Tour the Go interfaces you will implement most - fmt.Stringer, error, io.Reader, io.Writer, io.Closer, sort.Interface, http.Handler, json.Marshaler and flag.Value.

Go's standard library is built on a small number of tiny interfaces, many with exactly one method. Because interfaces are satisfied implicitly, you plug your own types into the whole ecosystem by adding a method or two: fmt prints them your way, sort orders them, net/http serves them, encoding/json encodes them, and io.Copy moves their bytes around.

This lesson walks through the interfaces you will meet and implement most often. For each one you will see the exact method set, a working implementation, and how the standard library uses it. Knowing these by heart makes Go code easier to read, because a method named Write(p []byte) (int, error) immediately says "this is a writer".

fmt.Stringer

fmt.Stringer has one method, String() string. When you print a value with %v or %s, or pass it to Println, fmt checks whether the value implements Stringer and, if so, calls it:

Go Teaching fmt how to print a type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice three things. %d still prints the underlying number, because %d asks for an integer. A slice of Point uses Point's String for each element. And %+v also calls String (only %#v bypasses it and prints Go syntax).

Do not call fmt.Sprintf("%v", d) or fmt.Sprint(d) with the receiver itself inside String(). That calls String again and recurses until the stack overflows. Convert first: fmt.Sprintf("%d", int(d)).

error

You have already used the most important interface of all. error is a built-in interface with a single method, Error() string:

Go
type error interface {
	Error() string
}

Any type with that method is an error. Errors as Values and Custom Error Types go deep; here is the minimum:

Go A type that satisfies error

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The first call prints <nil> because a nil error interface means success. The second returns a *OutOfStock; errors.As finds it so the caller can read its fields.

io.Reader, io.Writer and io.Closer

The io package defines the interfaces that make Go's I/O composable:

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

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

type Closer interface {
	Close() error
}

Read fills the slice p with up to len(p) bytes and returns how many it wrote. When there is nothing more, it returns 0, io.EOF. Write consumes all of p or returns an error. Files, network connections, HTTP bodies, compressors, buffers and strings all implement these, so you can chain them freely. Here is a reader that wraps another reader and shouts everything it passes along, plus a writer that counts bytes:

Go A Reader that wraps a Reader and a Writer that counts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

io.Copy knows only Reader and Writer. It has no idea that one transforms and the other counts, and it does not need to. This is the design Go calls composition: small pieces that snap together. io.Closer joins the family for resources that must be released, and the standard library combines them into io.ReadCloser, io.ReadWriter, io.ReadWriteCloser and so on by embedding interfaces.

If you implement Read yourself, be careful with the contract: return n > 0 data before or together with io.EOF, never return 0, nil forever, and never keep a reference to p after returning. To test a reader's behavior cheaply, testing/iotest provides awkward readers, and strings.NewReader or bytes.NewBuffer provide easy ones.

sort.Interface

Before generics, the way to sort a custom collection was to implement the three methods of sort.Interface:

Go
type Interface interface {
	Len() int
	Less(i, j int) bool
	Swap(i, j int)
}

You still see it in older code, and sort.Sort and sort.Stable accept it. (New code usually calls slices.SortFunc, covered in Sorting.)

Go Sorting through sort.Interface

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

byAge is just a defined slice type with three methods. Converting people to byAge costs nothing; it is the same memory with a different method set. sort.Reverse is itself a wrapper that implements sort.Interface by flipping Less, another small example of composition.

http.Handler

The whole net/http server model rests on one interface:

Go
type Handler interface {
	ServeHTTP(w ResponseWriter, r *Request)
}

Anything that can serve an HTTP request is a Handler. We cannot open real network ports here, but net/http/httptest lets us call a handler directly with a fake request and a recorder that remembers the response, and that is also how you test handlers in real projects:

Go A struct that is an http.Handler

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The handler is a struct with state, which is one reason handlers are interfaces and not just functions. For stateless handlers the standard library also offers the adapter type http.HandlerFunc, a function type with a ServeHTTP method that calls itself. Methods on function types are what make that possible. The web lessons later in the course build on all of this.

json.Marshaler and json.Unmarshaler

encoding/json normally walks a struct with reflection. If a type implements json.Marshaler (MarshalJSON() ([]byte, error)), the encoder calls your method instead. The mirror image is json.Unmarshaler. This is how you control the exact JSON for a type:

Go Controlling JSON with MarshalJSON and UnmarshalJSON

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice the receivers: MarshalJSON uses a value receiver so it works on both values and pointers, while UnmarshalJSON must use a pointer receiver because it assigns into the value. The same shape exists for text with encoding.TextMarshaler and encoding.TextUnmarshaler, which json also uses for map keys. See Value vs Pointer Receivers for the rule behind that choice.

flag.Value

The flag package parses command-line options, and you can add your own option types by implementing flag.Value:

Go
type Value interface {
	String() string
	Set(string) error
}

Set is called with the text from the command line; String shows the current value in help output. We have no real command line here, so the example builds a FlagSet and parses a slice of arguments you can see in the code:

Go A custom command-line flag type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Because *listFlag has both methods, &tags satisfies flag.Value. The built-in types flag.Int, flag.Duration and the rest are implemented the same way.

Other interfaces worth knowing

Once you recognize the pattern you will spot dozens more. A few that appear constantly:

Interface Method(s) Used by
io.ReaderFrom / io.WriterTo ReadFrom(r) / WriteTo(w) io.Copy fast paths
io.Seeker Seek(offset, whence) files, bytes.Reader
io.ByteReader, io.RuneReader ReadByte(), ReadRune() bufio, parsers
fmt.GoStringer GoString() string %#v printing
fmt.Formatter Format(f State, verb rune) full control over Printf verbs
encoding.TextMarshaler MarshalText() JSON keys, config formats
context.Context Deadline, Done, Err, Value cancellation
sort.Interface Len, Less, Swap sort.Sort
http.RoundTripper RoundTrip(*Request) HTTP client middleware

A good habit when you add a method that is meant to satisfy an interface: write a compile-time assertion next to the type, such as var _ fmt.Stringer = Point{} or var _ io.Writer = (*countWriter)(nil). It costs nothing at run time and turns a typo in the method name into an immediate compile error at the type, not a mysterious failure at a distant call site.

Go Compile-time interface checks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

fmt.Fprintf accepts any io.Writer, and Println found String on the pointer. Both worked without a single implements keyword.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which method makes a type print itself with fmt.Println(v)?

    fmt looks for fmt.Stringer, whose only method is String() string.
  2. 2. What does an io.Reader's Read return when the data has run out?

    The end of the stream is signalled with the sentinel error io.EOF. Returning 0, nil repeatedly is discouraged and can make callers loop forever.
  3. 3. Why does UnmarshalJSON use a pointer receiver while MarshalJSON can use a value receiver?

    A method with a value receiver works on a copy. Decoding has to modify the caller's value, which requires a pointer.
  4. 4. What is the purpose of var _ io.Writer = (*shout)(nil)?

    Assigning a typed nil pointer to a blank variable of the interface type forces a compile-time check without any run-time cost.
  5. 5. What happens if String() of type ID int calls fmt.Sprintf("%v", id) with its own receiver?

    %v calls String again on the same value. Convert to the underlying type first, for example fmt.Sprintf("%d", int(id)).

Summary

  • Many standard-library features are one-method interfaces: implement the method and your type plugs in.
  • fmt.Stringer (String() string) customizes %v and %s; error (Error() string) makes a value an error.
  • io.Reader, io.Writer and io.Closer compose: wrap readers and writers to transform or count data, and let io.Copy move it.
  • sort.Interface needs Len, Less and Swap; http.Handler needs ServeHTTP; json.Marshaler/Unmarshaler and flag.Value customize encoding and command-line parsing.
  • Use pointer receivers when the method must modify the value, and remember that a method set decides which interfaces a type or its pointer satisfies.
  • Add var _ Interface = (*T)(nil) to get compile-time proof that a type satisfies an interface.

Next: Interface Internals and the nil Trap looks at what an interface value really contains.