Skip to content

Interfaces

Intermediate · Types & Methods

Interfaces are the heart of Go’s polymorphism. An interface lists method signatures; any type with those methods satisfies it implicitly — no implements keyword. Interface values hold a (concrete type, value) pair.

  • interfaces1 — implicit satisfaction + polymorphism over []Shape
  • interfaces2fmt.Stringer and the compile-time var _ I = T{} check
  • interfaces3 — recovering the concrete type with a type switch / assertion
  • interfaces4 — interface embedding (ReadWriter = Reader + Writer)

An interface is a set of method signatures. A type satisfies it IMPLICITLY,

Show hint
Add an Area method to each type — no implements keyword needed:
func (r Rectangle) Area() float64 { return r.W * r.H }
func (c Circle) Area() float64 { return math.Pi * c.R * c.R }

Source

Implementing fmt.Stringer (String() string) controls how a value prints.

Show hint
Implement String() string to satisfy fmt.Stringer:
func (p Point) String() string { return fmt.Sprintf("(%d, %d)", p.X, p.Y) }

Source

Recover the concrete type held by an interface value with a type switch

Show hint
Type switch extracts the concrete type (import "fmt"):
switch x := v.(type) {
case int: return fmt.Sprintf("int: %d", x)
case string: return fmt.Sprintf("string: %s", x)
default: return "unknown"
}

Source

Interfaces can embed other interfaces. A type satisfies the combined

Show hint
Implement both methods on *Buffer to satisfy the embedded interface:
func (b *Buffer) Read() string { return b.data }
func (b *Buffer) Write(s string) { b.data += s }

Source