第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

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

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

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

Go
長風(fēng)秋雁 2023-07-26 15:37:56
Go 不支持多態(tài)性。如果要在泛型類型的保護下傳遞特定類型,則它無法在 Go 中工作。以下代碼引發(fā)錯誤。在 Go 中實現(xiàn)相同功能的最佳方法是什么?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條經(jīng)驗 獲得超6個贊

只是因為在本例中,Child 類型是由 Parent 組成的。并不意味著它就是那個東西。這是兩種不同的類型,因此不能以這種方式互換。

現(xiàn)在,如果您有一個接口 Parent 并且您的子對象滿足該接口,那么我們正在談?wù)撏耆煌氖虑椤?/p>

編輯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)


}


查看完整回答
反對 回復(fù) 2023-07-26
  • 1 回答
  • 0 關(guān)注
  • 166 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號