Skip to content
Codewilds

Lesson 26 of 38 · Interfaces & Errors

Go Interfaces: Implicit Implementation and Polymorphism

medium20 XP4 min read

In the last chapter you gave Rect and Circle their own Area methods. But a function that takes a Rect accepts only a Rect: to handle circles too, you'd need a second function, and a third one for triangles. Go interfaces solve this. A function can accept any type that behaves the right way — that is how Go does polymorphism without classes or inheritance.

Interfaces describe behaviour

An interface type is a set of method signatures, called a method set. It says nothing about data, only about what a value can do:

type Shape interface {
	Area() float64
	Perimeter() float64
}

A variable of type Shape can hold a value of any type that has both methods.

Implicit implementation

Go has no implements keyword. A type satisfies an interface automatically, simply by having the methods:

type Rect struct {
	Width, Height float64
}

func (r Rect) Area() float64      { return r.Width * r.Height }
func (r Rect) Perimeter() float64 { return 2 * (r.Width + r.Height) }

func main() {
	var s Shape = Rect{Width: 3, Height: 4} // fine: Rect has both methods
	fmt.Println(s.Area(), s.Perimeter())
}
12 14

Because a type never names the interfaces it satisfies, you can define an interface after the fact — even for types from the standard library — and packages stay independent of each other. If a method is missing or its signature differs, the compiler names the culprit: Rect does not implement Shape (missing method Perimeter).

Polymorphism with a slice of interfaces

An interface value stores a concrete value together with its type. Calling a method runs that type's method, so one loop can handle many types:

type Circle struct {
	Radius float64
}

func (c Circle) Area() float64      { return math.Pi * c.Radius * c.Radius }
func (c Circle) Perimeter() float64 { return 2 * math.Pi * c.Radius }

func main() {
	shapes := []Shape{Rect{Width: 3, Height: 4}, Circle{Radius: 1}}
	for _, s := range shapes {
		fmt.Printf("%.2f\n", s.Area())
	}
}
12.00
3.14

Add a Triangle with the same two methods tomorrow and this loop works with it unchanged.

Small interfaces

Go favours tiny interfaces, often with a single method. You have already met one: the String method of Celsius in the methods lesson made it a fmt.Stringer, which is why fmt.Println printed 21.5°C:

// in package fmt
type Stringer interface {
	String() string
}

Another famous one is io.Reader — just Read(p []byte) (n int, err error) — implemented by files, network connections, strings.Reader and many more. The smaller the interface, the more types can satisfy it.

Pointer receivers and method sets

The method set of a type T contains its value-receiver methods. The method set of *T contains both value- and pointer-receiver methods. So when a method has a pointer receiver, only the pointer satisfies the interface:

type Counter struct {
	N int
}

func (c *Counter) Inc() { c.N++ }

type Incrementer interface {
	Inc()
}

var a Incrementer = &Counter{} // OK: *Counter has Inc
var b Incrementer = Counter{}  // compile error: method Inc has pointer receiver

This rule protects you. A value stored inside an interface can't be addressed, so Go could only call Inc on a copy — and the increment would silently vanish.

The empty interface: any

interface{} has no methods, so every type satisfies it. any is its shorter alias:

var box any = 42
box = "now a string"
fmt.Println(box) // now a string

fmt.Println takes ...any, which is why it can print anything. But any tells the compiler nothing about the value: to use it as a string again, you need a type assertion (next lesson). Prefer a specific interface whenever you can.

nil interfaces

The zero value of an interface is nil: no type and no value inside. Comparing with nil is a handy way to say "no result", but calling a method on a nil interface panics:

var s Shape
fmt.Println(s == nil) // true
// s.Area() would panic: invalid memory address or nil pointer dereference

Common mistakes

  • Looking for implements: there is none — just write the methods.
  • Near-miss signatures: Area() int or area() float64 doesn't satisfy Area() float64. Names, parameters and results must match exactly.
  • Storing a value when the methods need a pointer: use &Counter{}, not Counter{}.
  • Using any everywhere: you lose the compiler's checks. Ask for the smallest interface your function needs.
  • Calling a method on a nil interface: check s == nil first.

Assignment

The island cartographers measure fields of every shape. Rect is finished — it's the one from the methods lesson. Complete the rest:

  1. Give Circle the methods Area() float64 (π × r²) and Perimeter() float64 (2 × π × r) so that it satisfies Shape. Use math.Pi and add "math" to the imports.
  2. Make Circle a fmt.Stringer: String() returns Circle(r=1.5) for a radius of 1.5. Format the radius with %g.
  3. TotalArea(shapes []Shape) float64 returns the sum of all areas (0 for an empty slice).
  4. Largest(shapes []Shape) Shape returns the shape with the biggest area. If several share the biggest area, return the first of them; for an empty slice, return nil.

Both functions must work only through the Shape methods — the tests also pass in a shape type you have never seen.

shapes := []Shape{Rect{Width: 3, Height: 4}, Circle{Radius: 1}}
TotalArea(shapes)                // 12 + π ≈ 15.14
Largest(shapes)                  // Rect{Width: 3, Height: 4}
fmt.Println(Circle{Radius: 1.5}) // Circle(r=1.5)

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Interfaces in other languages

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+20 XP

Lesson 26 is part of the full course. The first 9 lessons are free.

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.