How to implement polymorphism with embedded interfaces in Go?

To implement polymorphism with embedded interfaces in Go, you can follow these steps:

  1. Create the base interface that defines common behavior for multiple types. For example:
type Animal interface { Sound() string }
  1. Implement methods for each type that satisfies the base interface. For example:
type Dog struct{} func (d Dog) Sound() string { return "Woof" } type Cat struct{} func (c Cat) Sound() string { return "Meow" }
  1. Create a new interface that embeds the base interface along with any additional methods specific to that interface. For example, let's create an interface for pets:
type Pet interface { Animal Name() string }
  1. Implement the new interface for each type that satisfies it. For example:
type PetDog struct { Dog name string } func (p PetDog) Name() string { return p.name } type PetCat struct { Cat name string } func (p PetCat) Name() string { return p.name }
  1. You can now use polymorphism by treating instances of the embedded interface as instances of the base interface. For example:
func PrintAnimalSound(a Animal) { fmt.Println(a.Sound()) } func main() { dog := Dog{} cat := Cat{} petDog := PetDog{name: "Buddy"} petCat := PetCat{name: "Whiskers"} PrintAnimalSound(dog) // Output: Woof PrintAnimalSound(cat) // Output: Meow PrintAnimalSound(petDog) // Output: Woof PrintAnimalSound(petCat) // Output: Meow }

By using embedding, you can define common behavior in the base interface and extend it with additional methods in the embedded interface. This allows you to achieve polymorphism and reuse code across different types.