Simple Golang Introduction to Interfaces and Polymorphism
Simple Golang Introduction to Interfaces and Polymorphism
This is a very simple Golang (Go Programming) introduction to Interfaces and Polymorphism.
I will set an example to explain in simple terms how an interface is and how it relates to polymorphism. We will make the use of Go methods.
In Go (Golang programming) a value can be of one or more types.
For example:
Let's build a struct type with the identifier "insect". There are two fields in this struct namely "name" and "country" however they are not relevant to the example.
Let's also create a struct with the identifier "human" and also the inside fields are not of importance here.
In func.main we add 2 values of the types created above:
Now we need a method to print one of those values. Outside the func.main we create the "showResults()" function. Notice how the method can use the dot notations "i.name" and "i.country" to get parts of the values.
IMPORTANT! By using the receiver of type "insect" we are associating the "showResults()" method with the type "insect".
Let's now associate the type "human" with the same "showResults()" method by creating it. In this case we are not writing any code inside the method, we are just creating it and placing the receiver of type "human". Which is enough to make the relation.
We can use the method "showResults()" to print the first value which is "insect1" from func.main. This is normal use of a method in Golang.
Now let's create the interface, that will be in the main scope such as the structs were created. To create the interface we use "keyword identifier interface" as it follows. In the example below being is the name of the identifier. IMPORTANT! This interface is now linked to the method showResults() which means that other types (such as insect and human) that use the showResults() method are now also of type being!
Hence values insect1 and human1 which are using the showResults() method are now also of being type. Yes, insect1 is of type insect (as created in the insect struct) and human1 is of type human (as created in the human struct) but now, they are ALSO of type being.
To prove this we will create a function that takes an argument of type being.
However, since the types insect and human are associated with the showResults() method and the being interface is asking for showResults() method, we can now use values of insect or human type to be passed as arguments.
This is polymorphism. We have one interface with multiple (poly) different types.
I am not an advanced Go programmer hence my explanations might be lacking. Feel free to post a comment here and point out your view.