Interfaces in Go
Improve your knowledge of interfaces, their usage, and their interface composition.
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),io.Reader
, andio.Writer
.
Let’s look at a basic example:
Get hands-on with 1200+ tech skills courses.