Go doesn't support Polymorphism.If specific types were to be passed under the umbrella of Generic types it fails to work in Go. Following piece of code throws error . What is the best way to achieve the same functionality in Go?
package main
import (
"fmt"
)
type parent struct {
parentID string
}
type child1 struct {
parent
child1ID string
}
type child2 struct {
parent
child2ID string
}
type childCollection struct {
collection []parent
}
func (c *childCollection) appendChild(p parent) {
c.collection = append(c.collection, p)
}
func main() {
c1 := new(child1)
c2 := new(child2)
c := new(childCollection)
c.appendChild(c1)
c.appendChild(c2)
}
Just because the type Child is composed of something Parent in this case. does not mean that it is that something. These are two different types so cannot be interchangeable in this way.
Now if you had an interface Parent and your child objects meet that interface then we are talking a different thing altogether.
Edit 1
Example
https://play.golang.org/p/i6fQBoL2Uk7
Edit 2
package main
import "fmt"
type parent interface {
getParentId() (string)
}
type child1 struct {
child1ID string
}
func (c child1) getParentId() (string) {
return c.child1ID
}
type child2 struct {
child2ID string
}
func (c child2) getParentId() (string) {
return c.child2ID
}
type childCollection struct {
collection []parent
}
func (c *childCollection) appendChild(p parent) {
c.collection = append(c.collection, p)
}
func main() {
c1 := child1{"1"}
c2 := child2{"2"}
c := new(childCollection)
c.appendChild(c1)
c.appendChild(c2)
fmt.Println(c)
}