Go Interfaces Are Satisfied Implicitly by Having the Methods

In progress

A Go interface is a named set of method signatures. A type implements it simply by having those methods: there is no implements keyword and no declaration linking the two. Any value with the right methods can be passed where the interface is expected, which keeps packages decoupled: the code that defines an interface doesn't need to know the types that will satisfy it.

Example

type Animal interface {
    Says() string
    NumberOfLegs() int
}

type Dog struct{ Name string }
type Gorilla struct{ Name string }

func (d Dog) Says() string        { return "Woof" }
func (d Dog) NumberOfLegs() int   { return 4 }
func (g Gorilla) Says() string    { return "Ugh" }
func (g Gorilla) NumberOfLegs() int { return 2 }

func PrintInfo(a Animal) {
    fmt.Println("This animal says", a.Says(), "and has", a.NumberOfLegs(), "legs")
}

PrintInfo(Dog{Name: "Sam"})
PrintInfo(Gorilla{Name: "Koko"})

Neither Dog nor Gorilla mentions Animal. The compiler checks, at the call, that each has both methods.

Consequences

  • Define interfaces where they are used. The consumer declares the small interface it needs (io.Reader needs only Read); producers don't import it.
  • Small interfaces compose. One or two methods each, combined when needed (io.ReadWriter).
  • Method sets depend on the receiver. If a method has a pointer receiver (func (d *Dog) ...), only *Dog satisfies the interface, not Dog: PrintInfo(Dog{}) fails to compile while PrintInfo(&Dog{}) works.

References

Review cards

Flashcard Why is it beneficial to define interfaces where they are used in Go?

It keeps the interface small and specific to the consumer's needs, reducing coupling between packages and making the code more modular and maintainable.

Flashcard Dog's methods have pointer receivers. Why does PrintInfo(Dog{}) fail to compile while PrintInfo(&Dog{}) works?

Pointer-receiver methods belong only to *Dog's method set, so only *Dog satisfies the interface.

Quiz Which of the following is true about interfaces in Go?
  • Interfaces are implemented implicitly by having the methods.
  • Interfaces must be explicitly implemented using an implements keyword.
  • Interfaces can only be implemented by structs, not by functions or interfaces.
  • Interfaces are checked for implementation at runtime.

Interfaces in Go are checked for implementation at compile time, not runtime, and do not require an implements keyword.