Interfaces are the way for you to describe abstract behaviour, but what makes Go Interfaces so great? Well, it’s probably the first thing you learn about them, that they are implemented implicitly. You don’t need to explicitly specify about a type which interface it implements. This makes dependancy injection super easy in Go, leaving your code decoupled. You are defining the behaviour you need, and not what you do. Your type could implement more and more interfaces, without ever changing your code!

But when an interface depends on another one, you encounter a type dependancy, and not a behaviour one. In this post we’ll try to see why and how to handle this case.

When an interface is just a type.

So for a type to implement an interface, it must have all the interface’s methods. This means the methods’ names and signatures. Each method must take and return the exactly same type parameters. This strictness stays even if that parameter type is an interface.

Example

Imagine we have an application for running jobs. We want to separate the implementation of the job and the way the job runs.

For doing the job we will define a Worker interface, and for running the job we will define a Runner interface. Then we will compose these two interfaces in a separated package called runner :

package runner

	type Worker interface {
	  Do()
	}

	type Runner interface {
	  Run(Worker)
	}

	func Run(r Runner, w Worker) {
	  r.Run(w)
	}

So the package runner doesn’t do much except exporting a function for running a Worker. It doesn’t know anything about what the job is and how does it run.

#go #dependencies #golang #interfaces

When an Interface Depends on Another Interface in Go
1.15 GEEK