DEV Community

Discussion on: Polymorphism for Go slices

Collapse
 
peppy profile image
Peppy Sisay

Creative approach!

Another way is to type the slices as a list of Elements.

elements := []Element{
    MyCustomStruct1{prop1: "foo", prop2:"bar"},
    MyCustomStruct1{prop1: "foo1", prop2:"bar1"},
}
elements2 := []Element{
    MyCustomStruct2{"foo"},
    MyCustomStruct2{"bar"},
}
Enter fullscreen mode Exit fullscreen mode
func printElementList(elements []Element) {
    for _, e := range elements {
        fmt.Println(e.toString())
    }
}
Enter fullscreen mode Exit fullscreen mode

play.golang.org/p/qdbRJ1Kq_Kq

Collapse
 
vicentdev profile image
Vicent

Wow, yes, I think I tried to use polymorphism on the wrong way. The problem I see with that implementation is the elements in the slice can be another type that implements the same interface.