0

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())
    }
}
Sinan Ulker
  • 445
  • 8
  • 20
  • 1
    Also: Do not try to implement something like inheritance in Go. You will fail. Cat Dog Animal style programming in Go will only lead to frustration. Redesign. – Volker Sep 08 '18 at 06:31
  • I am still new on Golang, used to write php and C# so I think i need to read more go code and examples, thanks for the warning. – Sinan Ulker Sep 08 '18 at 21:15

0 Answers0