Interfaces in Go
Explore how Go interfaces serve as contracts defining behaviors, enabling dependency injection and flexible testing. Understand implicit implementation, multiple interfaces, and interface composition to write adaptable and testable code.
We'll cover the following...
To be able to test advanced scenarios, we need to improve our knowledge of interfaces and their composition. Interfaces are used to achieve dependency injection in programming, so it’s mandatory to have a clear idea of them and their usage. Moreover, they’re also one of the prerequisites for unit tests.
Interfaces
In Go, interfaces are normal values that define a specific behavior. They are collections of methods’ signatures and can be seen as contracts in which we state the provided capabilities. Each struct that implements the contract can be used as if it was an instance of that interface and passed throughout the codebase.
Note: In Go, the preference is specifying tiny interfaces with one or two methods that can easily be implemented by lots of structs. The three most used interfaces are
{}(empty interface), ...