This article explains embedding interfaces concept in golang. We first begin by writing the main crux of the code.
| |
In the above code, we declare a struct type named Dog. There is a method defined on the Dog struct called speak.
We declare a new struct Animal, which has Dog as one of its fields. Now, all the methods defined on the Dog struct can be accessed by creating a variable of type Animal (line 25).
Though this works fine, the problem is that the struct Animal has the Dog type hardcoded into it. If we want to include a Cat, we must alter the struct Animal to include Cat. It doesn’t end there—we also have to modify the variable initialization to include Cat. Since both Dog and Cat have the speak method, we must explicitly specify which function we intend to call. Code including Cat is shown below:
| |
To make it easy for us to swap between different animals, or include multiple animals, we can make use of Interfaces.
Interfaces
Step 1: Create a type of interface that encompasses the common functionalities
| |
Now, any type that implements the speak method is an implementation of the Language interface.
Step 2: Create a struct type Dog and implement the methods of the interface
| |
Step 3: Include the interface as a field in the Animal struct
| |
Now, any struct that implements the speak method can be assigned to the Language field during initialization. We don’t need to modify the Animal struct again.
Invoking the speak method for Dog is straightforward—just initialize the Animal variable with any implementation of the Language interface:
| |
Including a new animal is easy. All we have to do is create a new struct (e.g., Cat) and implement the speak() method on it:
| |
The real world advantage to doing this is that, now any time we decide to replace a functionality, say, we have included some customer specific logic, it is as easy as swapping it with the new struct that implements the interface.
Full code can be found below:
| |
In the main function (lines 27-32), Dog can be replaced by Cat, and by simply swapping the types, we can include Cat’s functionality instead of Dog’s.
The output is:
Meow