Polymorphism in Golang

Polymorphism is the ability to take on a variety of forms. In particular, in the previous articles, we discussed the use of interfaces which can correspond to different structures. For example:

package main

import "fmt"

// Action interface defines methods for a basic action
type Action interface {
    performAction()
}

// Person structure representing an individual
type Person struct {
    name string
}

// Animal structure representing an animal
type Animal struct {
    species string
}

// Implementing methods for the Person type
func (p *Person) performAction() {
    fmt.Printf("%s is speaking\n", p.name)
}

// Implementing methods for the Animal type
func (a *Animal) performAction() {
    fmt.Printf("The %s is moving\n", a.species)
}

func main() {
    john := &Person{name: "John"}
    tiger := &Animal{species: "Tiger"}

    entities := [...]Action{john, tiger}
    for _, entity := range entities {
        entity.performAction()
    }
}

In this scenario, an array of entities is defined, each of which corresponds to the Action interface. The entities consist of structures representing both Person and Animal objects. Essentially, an Action object can assume different forms, either as a Person structure or an Animal structure. When iterating over the array, the performAction method is called for each object. The actual type of the structure is dynamically determined during runtime, allowing the correct implementation of the performAction method for each specific structure to be invoked.

The output should be like this:

John is speaking
The Tiger is moving