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

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

在 golang 的另一個結構中重用結構

在 golang 的另一個結構中重用結構

Go
眼眸繁星 2023-05-15 10:09:41
我在 golang 中有兩個結構如下type Data struct {    Name          string    Description   string    HasMore   bool}type DataWithItems struct {    Name          string    Description   string    HasMore      bool    Items    []Items}至多DataWithItemsstruct 可以重寫為 type DataWithItems struct {        Info Data        Items []Items    }但是上面的內容使得將 json 對象解碼為DataWithItems. 我知道這可以通過其他編程語言的繼承來解決,但是Is there a way I can solve this in Go?
查看完整描述

2 回答

?
桃花長相依

TA貢獻1860條經驗 獲得超8個贊

您可以將一個結構“嵌入”到另一個結構中:


type Items string


type Data struct {

    Name        string

    Description string

    HasMore     bool

}


type DataWithItems struct {

    Data // Notice that this is just the type name

    Items []Items

}


func main() {

    d := DataWithItems{}

    d.Data.Name = "some-name"

    d.Data.Description = "some-description"

    d.Data.HasMore = true

    d.Items = []Items{"some-item-1", "some-item-2"}


    result, err := json.Marshal(d)

    if err != nil {

        panic(err)

    }


    println(string(result))

}

這打印


{"Name":"some-name","Description":"some-description","HasMore":true,"Items":["some-item-1","some-item-2"]}



查看完整回答
反對 回復 2023-05-15
?
Qyouu

TA貢獻1786條經驗 獲得超11個贊

只需使用一個結構 - DataWithItems,有時將項目留空



查看完整回答
反對 回復 2023-05-15
  • 2 回答
  • 0 關注
  • 134 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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