1 回答

TA貢獻1719條經驗 獲得超6個贊
只是因為在本例中,Child 類型是由 Parent 組成的。并不意味著它就是那個東西。這是兩種不同的類型,因此不能以這種方式互換。
現在,如果您有一個接口 Parent 并且您的子對象滿足該接口,那么我們正在談論完全不同的事情。
編輯1
例子
https://play.golang.org/p/i6fQBoL2Uk7
編輯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)
}
- 1 回答
- 0 關注
- 156 瀏覽
添加回答
舉報