I am getting deep into the Go architecture and I have problems with polymorphism. I simplified the problem and created new data for this example to be much more understandable my question.
I have this structure:
type Animal interface {
speak() string
}
type Cat struct {
Name string
}
type Dog struct {
Race string
}
And I want the structs to implement the interface, I proceed like that:
func (c Cat) speak() string {
return "Miaw!"
}
func (d Dog) speak() string {
return "Guau!"
}
func speak(a Animal) string {
return a.speak()
}
func speaks(a []Animal) string {
str := ""
for i := 0; i < len(a); i++ {
str += a[i].speak()
}
return str
}
So what I have created is:
The method speak
receives an Animal
and executes the method speak of the structure given (Animal
, which is Cat
or Dog
), and the method speaks
receive an slice of Animal
and executes the method speak of the structure given in every index of the slice (Animal
, which is Cat
or Dog
).
And for testing the methods, I implemented this function:
func test() {
cat1 := Cat{
Name: "Cat1",
}
cat2 := Cat{
Name: "Cat2",
}
cat3 := Cat{
Name: "Cat3",
}
arrayCats := []Cat{cat1, cat2, cat3}
speak(cat1)
speak(cat3)
speak(cat2)
speaks(arrayCats) //This line gives an error to the Compiler
}
I upload the error that the compiler gives to me:
Can someone please explain to me why I can play with polimorfish in a functions that receives only one element and why not in the function that receives an slice of that element?
I really need to find the solution to this problem to implement it in different parts of my application, and I have no idea how to solve the problem nor how to implement a practical and scalable solution (the slice in the real application will contain a hight number of elements).
I found this answers related useful to understand more my problem, but still I don't get what is the problem or the solution: Answer1 Answer2Answer3