Implicit implementation

A type implements an interface if it has the required methods. The word implements does not exist in the language.

An interface is a set of methods. A type implements it by itself, with no declaration:

type Stringer interface {
    String() string
}

Any type with a method String() string can be passed where fmt.Stringer is expected. The package that defined the type may not know about the interface. That lets you accept an interface in your own package and leave the implementation with the caller. The dependency points the right way: your code does not import a database and HTTP for the sake of a test.

The empty interface any (a synonym of interface{}) says nothing. You can put anything into it, and so it checks almost nothing. It belongs at the boundary of a truly universal container, fmt.Println, or json. In an ordinary API, any is a postponed type error.

An interface is satisfied by a method set, including the receiver. If a method is declared on a pointer, a value without a pointer does not implement the interface. The compiler says so at the assignment, not at runtime. That is a good error. Do not work around it through any.

Small interfaces combine. io.ReadCloser is Reader plus Closer. Almost nobody can implement a thick interface of ten methods in a test without a stub of hundreds of lines. If a test has to describe nine empty methods, the interface is lying about what it needs.

An interface name in Go often ends in -er when there is one method: Reader, Writer, Stringer. This is a convention, not a compiler rule. A name from the domain (UserStore) is better when there are several methods and the word er no longer explains anything.

Practice

  1. How to say "implements"

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

    • With the keyword implements
    • It does not. The required methods are enough
    • With the annotation //go:implements
    • By registering in init through reflect
  2. Which interface is convenient

    Mark the useful properties of an interface in ordinary service code.

    • Few methods, and the caller really needs all of them
    • Ten methods, so the interface does not have to grow later
    • The interface is declared by the caller, not inside the package of the single implementation
    • any everywhere, so you do not have to think about types
  3. A pointer and an interface

    The method Save() is declared on *Store. What implements an interface with the method Save()?

    • Both Store and *Store
    • Only *Store
    • Only Store
    • Neither, until you write implements