In Go, interfaces take the center stage. They are more flexible and more powerful than their counterparts in other languages. When coming to Go from a

A Guide to Interfaces in Go

submited by
Style Pass
2024-02-11 14:00:08

In Go, interfaces take the center stage. They are more flexible and more powerful than their counterparts in other languages. When coming to Go from another language, this may not be immediately obvious, yet this realization is quite important for our ability to write well-structured and decoupled code. Let’s explore exactly how flexible they are and how we can make the best use of them.

I’ll assume that you have at least a passing familiarity with the Go programming language and interfaces. In the following, I’ll be referring to both functions and methods. They are not the same, so you should know the difference[1][2]. Also, I’ll be referring to both parameters and arguments - again, not the same[3]. With that said, let’s Go!

Interfaces enable polymorphism[4], i.e. they allow us to ignore what type a variable has and instead focus on what we can do with it (the behavior that it offers us via its methods), we gain the ability to work with any type, provided that it satisfies the interface. Go’s interfaces are structurally typed, meaning that any type is compatible with an interface if that type is structurally equivalent to the interface. An interface and a type are structurally equivalent if they both define a set of methods of the same name, and where methods from each share the same number of parameters and return values, of the same data type. This stands in contrast to explicit interfaces that must be referenced by name from the type that implements it[5]. In essence, we say that the type satisfies the interface.

Leave a Comment