我在golang中有两个结构,如下所示
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
。我知道这可以通过其他编程语言中的继承来解决,但是Is there a way I can solve this in Go?
您可以将一个结构“嵌入”到另一个结构中:
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"]}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句