Interfaces · 3 MIN READ

The consumer declares the interface

Write the smallest interface a function needs, at the call site.

A type satisfies an interface by having the methods. There is no implements keyword and no import relationship, so a package can accept types that were written before its interface existed.

The idiom that follows: accept interfaces, return structs. And keep the interface as small as the function actually uses — one method is common and two is already a design decision.

SEE THE IDEA

The consumer defines the behavior it needs

  1. 01

    Consumer

    go
    type Reader interface { Read() }

    Declares a small contract

  2. 02

    Concrete type

    go
    func (s Source) Read()

    Supplies the matching method

  3. 03

    Assignment

    go
    var r Reader = Source{}

    Satisfaction is checked implicitly

No implements declaration connects the type to the interface.

In practice

Define the interface next to the function that consumes it, using only the methods that function needs. Existing types can then satisfy it without knowing about your package. A compile-time assignment to the interface is a useful way to document and check a type intended to satisfy it.

Watch out

Method names alone are insufficient. Parameter and result types must match the interface signature exactly.

Official reference ↗

Work through the exercise

go
package main

import "strings"

// summarise should accept anything that can report its own length,
// not just a strings.Builder.
func summarise(b *strings.Builder) int {
	return b.Len()
}

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.