Polymorphism is an ability of a thing to be displayed in multiple forms. For example, a human can be a child, an adult, a sibling, a parent, and so on. Thus, the same human exhibits different forms based on situations, and this is what we call polymorphism.
In a more technical term, polymorphism can be defined as a function that can be used for different types. However, that function must have different signatures.
In Go, we can implement polymorphism using interfaces
only.
Let's see an example in the code snippet below:
package main// importing package 'fmt'import "fmt"// creating an interface 'Language'type Language interface {getDevelopedBy() string}// creating a structure 'JavaScript'// that contains the fields required by interface 'Language'type JavaScript struct {DevelopedBy string}// implementing methods of interface 'Language'// for structure 'JavaScript'func (javaScript JavaScript) getDevelopedBy() string {return javaScript.DevelopedBy;}// creating a structure 'Python'// that contains the fields required by interface 'Language'type Python struct {DevelopedBy string}// implementing methods of interface 'Language'// for structure 'Python'func (python Python) getDevelopedBy() string {return python.DevelopedBy;}func main() {// creating an instance of interface 'Language'var ILanguage Language// creating an object of structure 'JavaScript'javaScript := JavaScript{DevelopedBy: "Brendan Eich"}// creating an object of structure 'Python'python := Python{DevelopedBy: "Guido van Rossum"}// assigning object 'javaScript' to 'ILanguage'// and invoking getDevelopedBy()ILanguage = javaScriptfmt.Println(ILanguage.getDevelopedBy())// assigning object 'python' to 'ILanguage'// and invoking getDevelopedBy()ILanguage = pythonfmt.Println(ILanguage.getDevelopedBy())}
fmt
.Language
.JavaScript
.Language
interface for the JavaScript
structure.Python
.Language
for the structure Python
.Language
.JavaScript
.Python
.javaScript
to ILanguage
and invoke the function getDevelopedBy()
.python
to ILanguage
and invoke the function getDevelopedBy()
.
JavaScript
and Python
, respectively. Both implement the interface Language
. getDevelopedBy()
and will display the DevelopedBy
value on the console.Since only one method was used for different objects, we can be sure that this is an example of polymorphism. Even if we add more types and implement the interface Language
for each of them, they will be able to invoke the function getDevelopedBy()
due to polymorphism.