Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 147 ยท Interfaces

Interfaces

Learn Go interfaces from scratch - implicit satisfaction, method sets, small interfaces, interface values, polymorphism, composing interfaces and io.Reader and io.Writer.

An interface describes behavior: a list of methods that a value must have. Any type that has those methods can be used wherever the interface is expected, and the type never has to say so. This is how Go does polymorphism, and it is the feature that most shapes idiomatic Go code. A function that takes an io.Reader works with files, network connections, strings, compressed streams and test data without knowing or caring which one it got.

What makes Go's interfaces unusual is that satisfaction is implicit. There is no implements keyword. If your type has the right methods, it satisfies the interface, even if the interface was written years later in a package your type has never heard of. This lesson covers declaring and using interfaces, how satisfaction is decided (with a link to method sets), what an interface value really holds, how to design small interfaces, how to compose them, and the two most important examples in the standard library, io.Reader and io.Writer.

Declaring and using an interface

An interface type lists method signatures. Here a Shape is anything that can report its area and perimeter:

Go Defining and using an 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.

Neither Rect nor Circle mentions Shape. They simply have the two methods, so they can be put in a []Shape and passed to describe. The %T verb prints the dynamic type stored inside each interface value, which leads to the next section.

Implicit satisfaction

A type satisfies an interface if its method set includes every method of the interface, with identical names and signatures. That check happens at compile time, wherever you try to use the value as that interface. If a method is missing, you get a precise error:

Go A missing method (fails on purpose)

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 compiler stops at the second assignment: cannot use Robot{} (value of struct type Robot) as Speaker value in assignment: Robot does not implement Speaker (missing method Speak). You will see this message often; it tells you exactly what to add.

Implicit satisfaction has a design consequence: the consumer defines the interface. The package that needs some behavior declares a tiny interface describing exactly that, and any type from anywhere can fit. The providing package does not need to know about it. More on this in Designing with Interfaces.

You can also ask the compiler to prove a type satisfies an interface, without creating a real variable, using a blank assignment. It is a common line near a type definition:

Go
var _ Speaker = Dog{}        // compile error here if Dog stops satisfying Speaker
var _ Speaker = (*Cat)(nil) // for pointer receivers

Method sets and pointer receivers

Which methods count? For a value of type T, only methods with a value receiver. For *T, methods of both kinds. So if a method has a pointer receiver, only the pointer satisfies the interface:

Go Pointer receivers and interfaces

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.

Passing Tally{} instead of &Tally{} fails with Tally does not implement Counter (method Inc has pointer receiver). This is by design: the interface would hold a copy, so Inc would update that copy and the caller would never see the change.

What an interface value holds

An interface value is a pair: a dynamic type and a dynamic value. When you assign a Rect to a Shape variable, the variable stores "type Rect, value {3 4}". Calling s.Area() looks up the method for the stored type and calls it. This is dynamic dispatch.

An interface variable that holds nothing is nil, with no type and no value. Calling a method on it panics:

Go Interface values: type and value (fails on purpose)

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 two lines show the empty interface: nil, type <nil>, value <nil>. After assigning a Square both parts are filled in. The last line panics with panic: runtime error: invalid memory address or nil pointer dereference followed by [signal SIGSEGV: segmentation violation ...]. There is a subtle trap where an interface holds a typed nil pointer and is not equal to nil; Interface Internals and the nil Trap explains it in depth.

Polymorphism in action

Polymorphism means one piece of code works with many types. With interfaces you write the algorithm once. This example sums areas and finds the biggest shape, and works for any current or future Shape:

Go Polymorphism with a slice of interfaces

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.

If tomorrow you add a Polygon type with an Area method, total and largest work with it unchanged. This is the open-closed principle without any class hierarchy.

Small interfaces are better

The most important Go proverb about interfaces is: the bigger the interface, the weaker the abstraction. The standard library's most useful interfaces have one method: io.Reader, io.Writer, fmt.Stringer, error. A one-method interface is easy to satisfy, easy to fake in tests and easy to understand.

Don't define an interface until you have a real need, usually two or more implementations or a test seam. Premature interfaces are noise. When you do, make them describe what the function needs, not everything the type can do:

Go A tiny interface that matches what the function needs

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.

GreeterFunc is a neat trick used in the standard library as http.HandlerFunc: give a function type a method so a plain function can satisfy a one-method interface.

Composing interfaces

Interfaces can embed other interfaces to build bigger contracts from small ones. The standard library does this everywhere: io.ReadWriter is io.Reader plus io.Writer. A type satisfies the combined interface if it has all the methods:

Go Composing interfaces

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.Reader and io.Writer: the model interfaces

The two interfaces every Go programmer must know are:

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

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

A Reader fills a byte slice and reports how many bytes it wrote, returning io.EOF at the end. A Writer consumes bytes. Functions like io.Copy(dst Writer, src Reader) work on files, sockets, buffers, HTTP bodies, gzip streams, hashes and your own types. Here is a custom Reader that upper-cases whatever it reads, wrapped around another reader, and then copied to standard output:

Go A custom io.Reader and io.Copy

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.

strings.NewReader produces a Reader, upperReader is a Reader wrapping it, and os.Stdout is a Writer. None of these types know about each other. That composability is the payoff of small interfaces. See Common Standard Interfaces for more.

Accept interfaces, return structs

A widely quoted guideline: function parameters should be interfaces; return values should be concrete types. Accepting an interface makes your function flexible and easy to test. Returning a struct keeps the full API available to callers, who can still assign it to any interface they choose. Returning an interface from a constructor hides methods and forces callers to guess the type. The usual exception is returning error, where the interface is the contract.

Name one-method interfaces after the method plus "er": Reader, Writer, Stringer, Closer. It signals that the interface is tiny.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How does a Go type declare that it implements an interface?

    Satisfaction is implicit. If the method set contains every method of the interface, the type satisfies it.
  2. 2. Given func (t *Tally) Inc() and type Counter interface { Inc() }, which assignment compiles?

    Only *Tally has Inc in its method set, so only the pointer satisfies Counter.
  3. 3. What does the %T verb print for var s Shape = Rect{1, 2}?

    %T prints the dynamic type held in the interface value, which here is main.Rect.
  4. 4. What happens when you call a method on a nil interface value?

    A nil interface has no dynamic type, so there is no method to call and the program panics.
  5. 5. Which design follows the advice "accept interfaces, return structs"?

    Taking an interface parameter such as io.Writer accepts many types, while returning a concrete *MemStore keeps its whole API visible.

Summary

  • An interface is a set of method signatures; types satisfy it implicitly by having those methods.
  • Satisfaction is checked at compile time using method sets: pointer-receiver methods only count for *T.
  • An interface value stores a dynamic type and value; a nil interface has neither and panics when called.
  • Prefer small interfaces defined where they are used, and compose bigger ones by embedding.
  • A function type with a method (like http.HandlerFunc) lets plain functions satisfy interfaces.
  • io.Reader and io.Writer show the power of tiny interfaces: wrappers and pipelines compose freely.
  • Accept interfaces, return concrete types.

Next: The Empty Interface and any