Go中的Supertype如何引用子类型

Go中的Supertype如何引用子类型

问题描述:

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)

}

Go Playground Link

Go不支持多态。如果要在Generic类型的保护下传递特定类型,它将无法正常工作 在Go中。 以下代码引发错误。 在Go中实现相同功能的最佳方法是什么? p>

 包main 
 
import(
“ fmt” 
)
 
type父结构{\  n parentID字符串
} 
 
type child1结构{
 parent 
 child1ID字符串
} 
 
type child2结构{
 parent 
 child2ID字符串
} 
 
type childCollection结构{
集合 [] 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)
 
} 
   pre> 
 
 

转到游乐场链接 p > div>

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)

}