Published on

Retrospectively Make a Struct Implement Your Interface in Go

Authors

I was trying to work out how to make a complex struct I am using from another library testable. I found the easiest was to define an interface for the struct methods I was using and then pass this interface to my method instead of the struct. Surprisingly this worked! Despite the fact that the struct was pulled in via a library and was in a different package to where I defined the interface.

func myMethodThatUsesStruct(someStruct *somePackage.SomeStruct) {
    stringReturnedByA := someStruct.methodA()
    ...
    someStruct.doSomething(personBAge)
}
....

type SomeStructInterface interface {
    func methodA() string
    func doSomething(age int)
}
func myMethodThatUsesStruct(someStruct SomeStructInterface) {
    stringReturnedByA := someStruct.methodA()
    ...
    someStruct.doSomething(personBAge)

Using this approach it was trivial for me to now define a mock that implements that interface and pass that around in my test.