In this program I'm saving references to the functions that are returning specific implementations in a slice.
Within SpeakAll I'm calling each function to get it's corresponding object and calling Speak on it.
Issue: Unable to iterate through array and get an output
package main
import "fmt"
type IAnimal interface {
Speak() string
}
type Cat struct {}
func (c Cat) Speak() string {
return "meow!"
}
type Dog struct {}
func (d Dog) Speak() string {
return "woof!"
}
type Zoo struct {
Animals []func() IAnimal
}
func (zoo Zoo) AddAnimal(animal func() IAnimal) {
if zoo.Animals == nil {
zoo.Animals = make([]func() IAnimal, 0)
}
zoo.Animals = append(zoo.Animals, animal)
}
func (zoo Zoo) SpeakAll() {
for _, animal := range zoo.Animals {
fmt.Println(animal().Speak())
}
}
func main() {
catFunc := func() IAnimal {return Cat{}}
dogFunc := func() IAnimal {return Dog{}}
z := Zoo{}
z.AddAnimal(catFunc)
z.AddAnimal(dogFunc)
z.SpeakAll()
}