0Pricing
Go Academy · Lesson

Interface Composition and Best Practices

Small interfaces and dependency inversion

Interface Composition

Go interfaces can embed other interfaces to compose larger ones:

package main
import "io"

// io.ReadWriter composes Reader and Writer
type ReadWriter interface {
    io.Reader
    io.Writer
}

// Your own composition:
type Processor interface {
    io.Reader
    Process() error
    io.Closer
}

func main() { _ = (*Processor)(nil) }

Small Interface Principle

The most powerful Go interfaces have one or two methods. This maximizes the number of types that can satisfy them:

  • io.Reader — 1 method
  • io.Writer — 1 method
  • error — 1 method
  • fmt.Stringer — 1 method

Large interfaces are harder to mock and test.

All lessons in this course

  1. Defining and Implementing Interfaces
  2. Core Standard Library Interfaces
  3. Type Assertions and Type Switches
  4. Interface Composition and Best Practices
← Back to Go Academy