Method overriding in Go

Jean-François Bustarret
Random Go tips
Published in
1 min readOct 26, 2015

[EDIT 10/30/2015 : rewrote most of the post for clarity and exactitude]

Everybody knows Go favors composition over inheritance. But Go also something that looks a little bit like method overriding, one feature of inheritance.

http://play.golang.org/p/EMh8ECV-Uu

As anonymous fields can be accessed by their type name, it is possible to call the “overriden” method from the outer struct :

http://play.golang.org/p/ZgnOQSSFw8

For each struct value, Go builds a table of pointers to all visible methods ; methods from inner structs are promoted to the outer struct (unless they already exists) and are included in this table.

This method table can then be matched to an interface definition to check if a value implements an interface.

There must be no ambiguity : if the same method is defined in two structs at the same level, an error is raised during compilation.

http://play.golang.org/p/qe7gK85UYs

Interface fields

The anonymous field can of an interface type, which is very useful when writing drivers/adapters stubs for unit tests :

The method table contains all implemented methods (with a valid pointer), but also unimplemented interface methods (with a nil pointer). Therefore calling unimplemented methods break at runtime with a “invalid memory address or nil pointer dereference” error :

http://play.golang.org/p/gW-dmk27oF

--

--