Method overriding in Go

[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.

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

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.

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 :
Like what you read? Give Jean-François Bustarret a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.