Interfaces and dynamic dispatch

An interface is a type made of method signatures. A variable of that type holds two things: the concrete type of the value and the value itself. Calling a method goes through that pair, which is dynamic dispatch, and it is the only inheritance-like mechanism Go has. The methods lesson gave types behaviour; an interface is how code calls that behaviour without naming the type.

A type and its methods

The interface lists what a caller needs, and any type with those methods satisfies it. There is no implements keyword and no registration: the compiler checks the method set at the assignment. A function that takes []Shape works on a new type the day it is written, without touching the function.

package main import "fmt" type Shape interface { Name() string Area() float64 } type Circle struct{ R float64 } func (c Circle) Name() string { return "circle" } func (c Circle) Area() float64 { return 3.14159 * c.R * c.R } type Rect struct{ W, H float64 } func (r Rect) Name() string { return "rect" } func (r Rect) Area() float64 { return r.W * r.H } func total(shapes []Shape) float64 { sum := 0.0 for _, s := range shapes { sum += s.Area() } return sum } func main() { shapes := []Shape{Circle{2}, Rect{3, 4}} for _, s := range shapes { fmt.Printf("%s %.2f %T\n", s.Name(), s.Area(), s) } fmt.Printf("total %.2f\n", total(shapes)) }

go run shape.go

circle 12.57 main.Circle
rect 12.00 main.Rect
total 24.57

The loop called two different Area methods through the same variable, and %T showed the concrete type behind each element. The interface value is two words wide: a type descriptor and a data pointer, which is why an interface never holds a value smaller than that pair without boxing it.

A nil interface is not a typed nil

An interface is nil only when both words are nil. Assigning a nil pointer of a concrete type fills the type word, so the interface is not nil and a method call dispatches to a method that may dereference nothing. That is the classic Go bug: a function returns (*myErr)(nil) as an error, the caller checks err != nil, and gets true.

package main import "fmt" type myErr struct{} func (e *myErr) Error() string { return "boom" } func main() { var plain error fmt.Println("plain nil:", plain == nil) var p *myErr var wrapped error = p fmt.Println("typed nil:", wrapped == nil) if wrapped != nil { fmt.Println("it looks like an error:", wrapped) } }

go run nil.go

plain nil: true
typed nil: false
it looks like an error: boom

The typed nil printed as an error because the type word was set; a caller cannot see that the value word is nil without a type assertion. The fix is to return an untyped nil from a function whose result type is the interface, not a nil pointer of the concrete type.

any and type assertions

any is an alias for interface{}: an interface with no methods, which every type satisfies. A value taken out of an any needs a type assertion, and the two-result form is the safe one: v.(T) panics when the dynamic type is not T, while v, ok := v.(T) reports false.

package main import "fmt" func main() { var v any = 42 n, ok := v.(int) s, sok := v.(string) fmt.Println(n, ok, s, sok) fmt.Println("is 42:", v == 42) var list []any = []any{1, "two", 3.5, true} for _, item := range list { fmt.Printf("%v is %T\n", item, item) } }

go run any.go

42 true false
is 42: true
1 is int
two is string
3.5 is float64
true is bool

The failed assertion gave 0 and false rather than a panic, which is why the comma-ok form belongs in every decoder. Comparing an interface to a concrete value compares the dynamic type first, so 42 and 42.0 are not equal through any.

The method set of T and of *T

A pointer receiver method belongs to *T, not to T, so a value of type T does not satisfy an interface that needs that method. A value can still call the method directly, because the compiler takes its address, but the interface assignment has no value to take the address of. This is the practical reason to keep one receiver kind per type.

package main import "fmt" type Loud struct{ n int } func (l *Loud) String() string { return "loud" } func main() { var a fmt.Stringer = &Loud{1} fmt.Println(a) var b fmt.Stringer = Loud{1} fmt.Println(b) }

go build -o methodset methodset.go

# command-line-arguments
./methodset.go:13:23: cannot use Loud{…} (value of struct type Loud) as fmt.Stringer value in variable declaration: Loud does not implement fmt.Stringer (method String has pointer receiver)

The message says which method and which receiver kind is missing, and the fix is &Loud{1} or a value receiver. The next lesson makes satisfaction explicit at compile time and switches on the dynamic type.

Exercises

  1. Add a Triangle to the shapes and print the total area without changing the total function. What would have to change in a language with inheritance?
  2. Write a function that returns a *myErr as an error and one that returns a plain nil. Compare the two results with == nil.
  3. Store a mix of ints and strings in a []any and sum only the ints with the comma-ok assertion. What does the failed assertion give for a string?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What does an interface value hold?

    Answer

    A dynamic type and a value of that type

    The pair is what makes dispatch and type assertions possible.

  2. What does this program print? package main import "fmt" type Shape interface { Name() string Area() float64 } type Circle struct{ R float64 } func (c Circle) Name() string { return "circle" } func (c Circle) Area() float64 { return 3.14159 * c.R * c.R } type Rect struct{ W, H float64 } func (r Rect) Name() string { return "rect" } func (r Rect) Area() float64 { return r.W * r.H } func total(shapes []Shape) float64 { sum := 0.0 for _, s := range shapes { sum += s.Area() } return sum } func main() { shapes := []Shape{Circle{2}, Rect{3, 4}} for _, s := range shapes { fmt.Printf("%s %.2f %T\n", s.Name(), s.Area(), s) } fmt.Printf("total %.2f\n", total(shapes)) }

    Answer

    circle 12.57 main.Circle / rect 12.00 main.Rect / total 24.57

    %T prints the package-qualified concrete type behind the interface, and the areas add up to 24.57.

  3. When is an interface value nil?

    Answer

    When both its dynamic type and its value are nil

    Assigning a nil pointer of a concrete type sets the type word, so the interface is not nil.

  4. What does this program print? package main import "fmt" type myErr struct{} func (e *myErr) Error() string { return "boom" } func main() { var plain error fmt.Println("plain nil:", plain == nil) var p *myErr var wrapped error = p fmt.Println("typed nil:", wrapped == nil) if wrapped != nil { fmt.Println("it looks like an error:", wrapped) } }

    Answer

    plain nil: true / typed nil: false / it looks like an error: boom

    The typed nil fills the type word, so the interface is not nil and its method prints boom.

  5. What happens when a failed type assertion is written without the comma-ok form?

    Answer

    The program panics

    v.(T) panics when the dynamic type is not T; v, ok := v.(T) reports false instead.

  6. What does the fourth line of this program print? package main import "fmt" func main() { var v any = 42 n, ok := v.(int) s, sok := v.(string) fmt.Println(n, ok, s, sok) fmt.Println("is 42:", v == 42) var list []any = []any{1, "two", 3.5, true} for _, item := range list { fmt.Printf("%v is %T\n", item, item) } }

    Answer

    42 true false / is 42: true / 1 is int / two is string / 3.5 is float64 / true is bool

    %T prints the dynamic type of the value stored in the interface.

  7. Which interface does every type satisfy?

    Answer

    any, which is interface{}

    An interface with no methods has nothing to fail, so every type satisfies it.

  8. What does the compiler say about this program? package main import "fmt" type Loud struct{ n int } func (l *Loud) String() string { return "loud" } func main() { var a fmt.Stringer = &Loud{1} fmt.Println(a) var b fmt.Stringer = Loud{1} fmt.Println(b) }

    Answer

    cannot use Loud{…} (value of struct type Loud) as fmt.Stringer value in variable declaration: Loud does not implement fmt.Stringer (method String has pointer receiver)

    The method set of Loud does not include String, because String has a pointer receiver.

  9. Why is a slice of interfaces a useful function parameter?

    Answer

    It lets one function call the same method on values of different concrete types

    That is dynamic dispatch: the call site names the method, the value decides the code.

  10. What does the comma-ok assertion give when the type does not match?

    Answer

    The zero value of the asserted type and false

    The failed assertion is reported, not fatal, which is what decoders use.

The code on this page was run with go 1.26.10 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev

Banner image