Go interface study


By: Axe 2019-09-25

Define an interface

type name interface {
  methodName(parameters) returnValues
}

From Effective Go document:

By convention, one-method interfaces are named by the method name plus an -er suffix or similar modification to construct an agent noun: Reader, Writer, Formatter, CloseNotifier etc.

e.g.

type Maker interface {
  hasName(name string) bool
}

Use the Interface

One weird part in go interface to me is the interface has to bind to an instance of a struct instead of the entire struct type, for example if I have defined a struct and a struct method as below:

type AxeMaker struct {
  name string
}

func (am *AxeMaker) hasName (name string) bool {
  return am.name == name
}

To use the interface with the struct we have to make an instance of the struct and declare the interface as variable then assign the struct instance to the interface. This process to me is like bind an interface to an implementation in a IoC container.

axeMaker := &AxeMaker { "Master X" }
var maker Maker
maker = axeMaker
maker.hasName("Master Y")