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 :

Random Go tips

Random Go tips

Jean-François Bustarret

Written by

IT Architect @ Objenious, blogging about Go

Random Go tips

Random Go tips

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade