Interfaces & Polymorphism — Go

An interface is a list of methods: type Bill interface { Total() int }. Any type with that method satisfies it automatically, without implements, and the…

A receipt at Bimo's Meatball Stall is a mix: a meatball order, a delivery fee, maybe a packing charge later. Each has a different type. How can one function add them all up?

The till asks every line on the receipt only one thing: "what's your total?". Anything can go on the receipt, as long as it can answer that question. Nobody has to sign up first: have the answer, and you're in. In Go, that question is written as an interface: a list of methods a type must have, whatever is inside it.

An interface: the list of methods it asks for

package main

import "fmt"

type Bill interface {
	Total() int
}

type Order struct {
	Menu     string
	Price    int
	Portions int
}

func (o Order) Total() int {
	return o.Price * o.Portions
}

type Delivery struct {
	Distance int
}

func (d Delivery) Total() int {
	return 2 * d.Distance
}

func totalDue(items []Bill) int {
	sum := 0
	for _, t := range items {
		sum += t.Total()
	}
	return sum
}

func main() {
	items := []Bill{
		Order{Menu: "Tendon Meatballs", Price: 15, Portions: 2},
		Delivery{Distance: 3},
	}
	for _, t := range items {
		fmt.Printf("%T %d\n", t, t.Total())
	}
	fmt.Println("total:", totalDue(items))
}
$ go run stall.go
main.Order 30
main.Delivery 6
total: 36

The compiler checks the contract. Remove the Total method from Delivery, and Go refuses:

cannot use Delivery{…} (value of struct type Delivery) as Bill value in array or slice literal: Delivery does not implement Bill (missing method Total)

Write Total() float64 and the reason becomes (wrong type for method Total), followed by have Total() float64 and want Total() int. The name, parameters and result type must match exactly.

The exercise uses the same pattern: an interface Shape with Area() float64, Circle{R: 5} (3.14 × 5 × 5 = 78.5) and Rectangle{W: 4, H: 6} (4 × 6 = 24), then totalArea(shapes []Shape) float64 adds them all up to 102.5.

What an interface value holds: a type and a value

A variable of an interface type holds two things: the real type and its value. In the first round t holds (Order, {Tendon Meatballs 15 2}), in the second (Delivery, {3}). When t.Total() is called, Go runs the method of the real type.

any and type assertions

The interface with no methods, interface{}, is satisfied by every type. Since Go 1.18 it has a short alias: any. An any variable can hold anything, but Go doesn't know what's inside, so you can't use it directly: var x any = 42 and then x + 1 is refused with invalid operation: x + 1 (mismatched types any and untyped int).

To get the real value back, use a type assertion x.(T):

var x any = "hello"

s := x.(string)  // "hello"
n, ok := x.(int) // 0 false: not an int, but no panic
m := x.(int)     // panic
panic: interface conversion: interface {} is string, not int

Type switches

Want to handle several types at once? Use a type switch:

func describe(x any) {
	switch v := x.(type) {
	case string:
		fmt.Println("text:", v)
	case int:
		fmt.Println("number:", v+1)
	default:
		fmt.Printf("other type: %T\n", v)
	}
}

describe("hello") prints text: hello, describe(42) prints number: 43 (in the int branch, v already has type int, so you can add to it), and describe(Delivery{Distance: 3}) prints other type: main.Delivery.

📌 A nil interface and an interface holding a nil pointer

An interface is nil only when its type and its value are both empty:

var p *Delivery                 // a nil pointer
var t Bill = p                  // type: *Delivery, value: nil
fmt.Println(p == nil, t == nil) // true false

t already has a type (*Delivery), so t == nil is false even though it holds a nil pointer. This often lets if err != nil through when there is no error, if a function returns a nil pointer as an error.

⚠️ Why is the type refused, or why does the program panic?

TL;DR: An interface is a list of methods: type Bill interface { Total() int }. Any type with that method satisfies it automatically, without implements, and the compiler refuses a type that lacks a method (missing method Total). A function that takes []Bill can call Total() on any type (polymorphism), like totalArea in the exercise adding a Circle and a Rectangle up to 102.5. An interface value holds the real type and its value. any (interface{}) holds anything, but you get it out with a type assertion: x.(int) panics if wrong, n, ok := x.(int) gives 0 false. A type switch switch v := x.(type) handles several types. An interface holding a nil pointer is not nil.

⚡ An interface is a list of methods

Write:

type Bill interface {
	Total() int
}

func (d Delivery) Total() int {
	return 2 * d.Distance
}

Meaning: Any type that has a method Total() int is a Bill automatically. There's no implements keyword like in Java. If a method is missing, the compiler refuses with missing method Total.

⚡ One call, many types

Write:

for _, t := range items {
	sum += t.Total()
}

Meaning: items is a []Bill holding a mix of Order and Delivery. The loop only calls t.Total(), and Go runs the method of the real type.

⚡ Getting a value out of any

Guess first: var x any = "hello", then n, ok := x.(int). Does the program panic?

No. The comma-ok form gives n = 0 and ok = false. What panics is x.(int) without ok.

Meaning: any can hold anything, but you get the value out with a type assertion x.(T) or a type switch.

What you will learn