亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Go中子類型如何被超類型引用

Go中子類型如何被超類型引用

Go
長風秋雁 2023-07-26 15:37:56
Go 不支持多態性。如果要在泛型類型的保護下傳遞特定類型,則它無法在 Go 中工作。以下代碼引發錯誤。在 Go 中實現相同功能的最佳方法是什么?package mainimport ("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)}
查看完整描述

1 回答

?
慕俠2389804

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)


}


查看完整回答
反對 回復 2023-07-26
  • 1 回答
  • 0 關注
  • 156 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號