To implement polymorphism with embedded interfaces in Go, you can follow these steps:
type Animal interface {
Sound() string
}
type Dog struct{}
func (d Dog) Sound() string {
return "Woof"
}
type Cat struct{}
func (c Cat) Sound() string {
return "Meow"
}
type Pet interface {
Animal
Name() string
}
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
}
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.