Interfaces in Go


Introduction to Go Interfaces

  • A Go interface defines one or more methods.
  • Unlike other languages, you don’t have to explicitly declare that a type implements an interface. A struct S is a thing which is defined by an interface I as long as the struct S implements all the methods defined by the interface I. In this example,FlyWithWings and FlyWithSuperPower are both FlyBehaviour as they all implement the methods defined in the interface FlyBehaviour.

Best Practice (a.k.a. Arguments)

“The smaller the interface,the stronger the abstraction”

"Accept interfaces but return structs”

“Go interfaces generally belong in the package that uses values of the interface type, not the package that implements those values”

“It can be useful to define a default abstraction on the producer side”

  • The implementation user.Manager is exposed and returned, which gives consumers the freedom to define the abstraction of user.ManagerInterface base on this implementation.
  • The package user provides a default abstraction of user.Manager and its mocks through the interface user.ManagerInterface and the struct user.ManagerMock, which frees some consumers from defining the abstraction ofuser.Manager and its mocks.
  • This pattern is a trade-off of the argument about where to define interfaces. That is, provide default abstraction on the producer side but also give consumers the freedom to define their own abstraction. And most importantly, let consumers decide what they want to use.





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