Random Go tips
Published in

Random Go tips

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.

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

--

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Jean-François Bustarret

Jean-François Bustarret

IT Architect @ Objenious, blogging about Go

More from Medium

Level-based logging in Go with Uber Zap

What is go.mod?

Creational Design Patterns in Golang

Unit Testing & Debugging Setup For Golang with VS Code