Interfaces Cheatsheet

Basic Definition

type Name interface {
    Method(param Type) ReturnType
}

Key Rules

  • Implicit Implementation: No implements keyword. If the methods exist, the interface is fulfilled.
  • Empty Interface: interface{} (or any) is implemented by every type.
  • Methods ONLY: Interfaces cannot contain fields, only method signatures.

Type Conversions

  • Assertion: v, ok := i.(Type) (Safely access concrete type)
  • Switch:
    switch v := i.(type) {
    case TypeA: // ...
    case TypeB: // ...
    }

Design Principles

  • Small: Aim for 1–3 methods.
  • Anonymous Parameters: Not recommended in interfaces (name them for clarity).
  • Embedded: You can embed one interface into another to combine their requirements.

Standard Library Examples

  • fmt.Stringer: String() string
  • io.Reader: Read(p []byte) (n int, err error)
  • error: Error() string