Let's say we have an interface and some structs that implements its method so in the main method we can call them in an interface slice by typing their name.
So my question is how can we get all the structs that implements Animal interface so I do not need hard-code the name of every struct?
package main
import (
"fmt"
)
type Animal interface {
Speak() string
}
type Dog struct {
}
func (d *Dog) Speak() string {
return "Woof!"
}
type Cat struct {
}
func (c *Cat) Speak() string {
return "Meow!"
}
func main() {
animals := []Animal{ &Dog{}, &Cat{} }
for _, animal := range animals {
fmt.Println(animal.Speak())
}
}