If you come from a C# background, you will find Go Interfaces like entities from another planet. My recommendation is to think about the interface in the literal sense, regardless of the programming language constructs.
I came up with this list to better describe Go interfaces:
- Go has no classes. Let that sink in a little bit; in C#/Java an interface is almost always attached to an implementor class.
- Go only has structs.
- There is no syntax to implement an interface. There is no
class Foo : IFooor
Foo implements Foo
- For a struct to be a correct implementation of an interface, it only has to have those methods.
Imagine you have these couple of classes in C#:
public class Elephant
At some point you think, “hey those are the same method, I can make an abstraction and create:”
public interface IAnimal
And then you do:
public class Elephant : IAnimal
And you’re being a great OOP Engineer™. In Go, you don’t need to go back and add that interface to those classes. When you created those classes with
Eat, they fulfilled
IAnimal interface in Go’s compiler eyes.
This is how it looks in Go:
Because both Tiger and Elephant have a method declaration, in Go land they are implementers of an Animal interface.
This idea implicit interface implementation is so powerful in Go; you will encounter interfaces with only one method, and this will be normal.
I created the Gopher image with https://gopherize.me/