« Back to Index

[Go Interface Design]

View original Gist on GitHub

Tags: #tags: go, interface

Go Interface Design.md

The rule of thumb when writing Go code is:

accept interfaces, return structs

Accepting interfaces gives your API the greatest flexibility
and returning structs allows the people reading your code to quickly navigate to the correct function.

Avoid concrete types in favour of interface types.

When you know the required functionality of a package, codify it into a interface.
Then check there isn’t already an interface in the stdlib that defines those behaviours.

A good blog post to refer to is: https://www.goinggo.net/2016/10/avoid-interface-pollution.html

In that it shows an example where an interface was unnecessary, in that it:

  1. it described the complete concrete implementation
  2. wasn’t decoupling the code from change
  3. could be removed and nothing changed for the user

The author suggests using an interface in these circumstances: