在golang中的另一个结构中重用结构

时间:2018-11-28 21:43:13

标签: go struct

我在golang中有两个结构,如下所示

type Data struct {
    Name          string
    Description   string
    HasMore   bool
}

type DataWithItems struct {
    Name          string
    Description   string
    HasMore      bool
    Items    []Items
}

最多DataWithItems结构可以重写为

 type DataWithItems struct {
        Info Data
        Items []Items
    }

但是,当将json对象解码为DataWithItems时,上述方法变得很困难。我知道可以通过其他编程语言中的继承来解决,但是Is there a way I can solve this in Go?

2 个答案:

答案 0 :(得分:1)

只需使用一种结构-DataWithItems,有时将项目留空

答案 1 :(得分:1)

您可以将一个结构“嵌入”到另一个:

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"]}
相关问题