在golang的另一个结构中重用结构
我在golang有两个结构,如下所示在golang的另一个结构中重用结构,go,struct,Go,Struct,我在golang有两个结构,如下所示 type Data struct { Name string Description string HasMore bool } type DataWithItems struct { Name string Description string HasMore bool Items []Items } 最多可以将DataWithIte
type Data struct {
Name string
Description string
HasMore bool
}
type DataWithItems struct {
Name string
Description string
HasMore bool
Items []Items
}
最多可以将DataWithItems
struct重写为
type DataWithItems struct {
Info Data
Items []Items
}
但上述情况使得将json对象解码为
DataWithItems
时变得困难。我知道这可以通过其他编程语言中的继承来解决,但是有没有办法在Go中解决呢?只需使用一个结构-DataWithItems,有时将items保留为空只需使用一个结构-DataWithItems,有时将items保留为空您可以将一个结构“嵌入”到另一个结构中:
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"]}
您可以将一个结构“嵌入”到另一个结构中:
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"]}
只要没有名称冲突,您也可以直接引用
DataWithItems
中的Data
字段。例如d.Name
有效。@HenryWoody非常正确!我永远也说不出我更喜欢哪种可读性。你也可以直接引用DataWithItems
中的Data
字段,只要没有名称冲突。例如d.Name
有效。@HenryWoody非常正确!我永远也说不出我更喜欢哪一种可读性。